diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..599b334 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +/.github export-ignore +/tests export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/phpunit.xml.dist export-ignore +/art export-ignore +/node_modules export-ignore +/resources/js export-ignore +/package.json export-ignore +/package-lock.json export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a4ef751 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: ci +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - statamic: "^5.0" + testbench: "9.*" + php: "8.2" + - statamic: "^5.0" + testbench: "10.*" + php: "8.3" + - statamic: "^6.0" + testbench: "10.*" + php: "8.3" + - statamic: "^6.0" + testbench: "11.*" + php: "8.4" + name: Statamic ${{ matrix.statamic }} / Testbench ${{ matrix.testbench }} / PHP ${{ matrix.php }} + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: intl, exif, gd + coverage: none + - name: Install + env: + COMPOSER_NO_SECURITY_BLOCKING: "1" + run: | + # Older Laravel and Statamic releases have security advisories, and + # Composer refuses those by default. They are tested on purpose; + # sites choose their own versions. + php -r '$c = json_decode(file_get_contents("composer.json"), true); $c["config"]["audit"]["block-insecure"] = false; $c["config"]["policy"]["advisories"]["block"] = false; file_put_contents("composer.json", json_encode($c, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));' + composer require "statamic/cms:${{ matrix.statamic }}" --no-interaction --no-update + composer require --dev "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --prefer-dist --no-interaction --no-progress --with-all-dependencies + - run: vendor/bin/phpunit + + bundle: + runs-on: ubuntu-latest + name: dist is up to date + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm ci && npm run build + - run: git diff --exit-code dist diff --git a/.github/workflows/release-notify.yml b/.github/workflows/release-notify.yml new file mode 100644 index 0000000..175ac3e --- /dev/null +++ b/.github/workflows/release-notify.yml @@ -0,0 +1,15 @@ +# Posts each published release of this repo to Slack, using the shared +# workflow in hibira-io/.github. Needs the org secret SLACK_WEBHOOK_URL; +# without it the job is a no-op. +name: release-notify + +on: + release: + types: [published] + +permissions: {} + +jobs: + slack: + uses: hibira-io/.github/.github/workflows/release-slack.yml@main + secrets: inherit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..78bd798 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/vendor/ +/composer.lock +/.phpunit.cache/ +/.phpunit.result.cache +/workbench/ +/testbench.yaml +/node_modules/ +/tests/__fixtures__/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5c3124d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 0.1.0 + +- Avatars of everyone who has the same entry open, and a warning when one + of them saves it. +- Live comments on entries, stored as one JSON file per entry: add, + resolve, reopen and delete, checked against Statamic's permissions. +- Live preview on other devices: a QR code and link of your live preview, + which reloads on every change. +- With `BROADCAST_CONNECTION=hibira`, Statamic's own control panel Echo + client connects to Hibira. +- Statamic 5 and 6. English, 繁體中文, 简体中文, 日本語, 한국어, ไทย and Tiếng Việt. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2acb880 --- /dev/null +++ b/README.md @@ -0,0 +1,119 @@ +# hibira-io/statamic + +[![ci](https://github.com/hibira-io/statamic/actions/workflows/ci.yml/badge.svg)](https://github.com/hibira-io/statamic/actions/workflows/ci.yml) + +Realtime teamwork for the [Statamic](https://statamic.com) control panel, on +[Hibira](https://hibira.io): + +- **Who else is here.** The avatars of everyone who has the same entry open, + and a warning the moment one of them saves it, so nobody keeps editing an + old version. +- **Live comments.** Leave a question or a note on an entry. Everyone who has + it open sees new comments as they are written; resolve them when they are + done. Reviewers who may only view an entry can comment too. +- **Live preview on any device.** Scan a QR code to open your live preview on + your phone, or send the link to another browser. The page reloads every + time you change the entry, and keeps its scroll position. + +Works with Statamic 5 and 6, flat file or database. Comments need no +database, and there is nothing to publish or build. + +![The dock, comments and a saved warning](art/comments-light.png) + +## Install + +```sh +composer require hibira-io/statamic +php artisan hibira:install +``` + +`hibira:install` (from [hibira-io/laravel](https://github.com/hibira-io/laravel)) +adds the `HIBIRA_*` settings to `.env`. Copy the app ID, key and secret from +your app page on [hibira.io/portal](https://hibira.io/portal) (the free plan +needs no card), and check them with `php artisan hibira:check`. + +On the same app page, add your site's address (for example +`https://example.com`) to **Allowed origins**, so the control panel and +preview pages may connect. + +Open an entry in two browsers, signed in as two users. The dock appears in +the bottom right corner. + +![Live preview on another device, in dark mode](art/preview-dark.png) + +## What it does + +| | | +| --- | --- | +| Avatars | Everyone with the entry's edit page open. Hover for the name. | +| Saved warning | When someone else saves the entry, a card asks you to reload before you edit. Saves from the console (imports, scheduled publishing) are left out. | +| Comments | Plain text, up to 2,000 characters. Ctrl+Enter sends. Anyone who may view the entry can comment and resolve; the author or a super user can delete. | +| Live preview link | Open Live Preview on the entry once, then press the phone button for the QR code and link. The link works as long as Statamic's live preview token. | + +People see only entries they may view: every channel subscription and +comment request is checked against Statamic's own permissions. + +In English, 繁體中文, 简体中文, 日本語, 한국어, ไทย and Tiếng Việt, following +each user's control panel language. + +## Options + +Publish the config to change them: + +```sh +php artisan vendor:publish --tag=hibira-statamic-config +``` + +| Setting | Default | | +| --- | --- | --- | +| `presence` | `true` | Avatars and saved warnings (`HIBIRA_STATAMIC_PRESENCE`) | +| `comments.enabled` | `true` | Comments (`HIBIRA_STATAMIC_COMMENTS`) | +| `comments.path` | `storage/statamic/hibira-comments` | One JSON file per entry. Point it inside `content/` to keep comments in git with your content. | +| `comments.max_length` | `2000` | Characters per comment | +| `live_preview` | `true` | Live preview on other devices (`HIBIRA_STATAMIC_LIVE_PREVIEW`) | +| `control_panel_echo` | `true` | See below (`HIBIRA_STATAMIC_CP_ECHO`) | + +### Statamic's own broadcasting + +Statamic's control panel has its own Echo client, which addons such as +[statamic/collaboration](https://github.com/statamic/collaboration) use. +Statamic only knows how to point it at Pusher or Reverb. With +`BROADCAST_CONNECTION=hibira`, this addon fills in the Hibira host, so those +addons run on Hibira with no more setup. That client opens a connection on +every control panel page, so set `HIBIRA_STATAMIC_CP_ECHO=false` if you +don't use such an addon. + +## How it uses Hibira + +- Each entry has a presence channel. The control panel signs subscriptions + on its own route, for users who may view the entry, so you don't have to + change your app's broadcasting setup. +- Comments are stored first, then sent to the others on the entry's channel. + A page that lost its connection fetches them again when it reconnects. +- A live preview page opened outside the control panel listens on a public + channel named after a keyed hash of its preview token, so only someone with + the link can find it, and its events carry no content. Events are sent only + while such a page is open. +- Each open edit page is one connection, and each preview page opened on + another device is one more. + +## Testing + +```sh +composer test +``` + +The browser code is in `resources/js`. After changing it, rebuild `dist/` +with `npm ci && npm run build`. + +## License + +MIT + +## 中文摘要 + +在 Statamic 控制台加上即時協作:同一篇內容誰也開著(頭像),有人儲存時立刻提醒重新載入; +即時留言(可標記已解決,只能看不能改的審稿人也能留言);用手機掃 QR Code 開即時預覽, +每次修改內容手機頁面就自動重新載入。支援 Statamic 5 與 6,留言存成 JSON 檔不需要資料庫。 +安裝:`composer require hibira-io/statamic`,`php artisan hibira:install` 填入 +[hibira.io/portal](https://hibira.io/portal) 的 App ID、Key、Secret,並把網站網址加到 Allowed origins。 diff --git a/art/comments-light.png b/art/comments-light.png new file mode 100644 index 0000000..013f1d8 Binary files /dev/null and b/art/comments-light.png differ diff --git a/art/preview-dark.png b/art/preview-dark.png new file mode 100644 index 0000000..75da864 Binary files /dev/null and b/art/preview-dark.png differ diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b500735 --- /dev/null +++ b/composer.json @@ -0,0 +1,77 @@ +{ + "name": "hibira-io/statamic", + "description": "Live comments, \"someone else is editing\" warnings and live preview on any device for the Statamic control panel, over Hibira WebSockets", + "type": "statamic-addon", + "keywords": [ + "statamic", + "statamic-addon", + "laravel", + "comments", + "collaboration", + "presence", + "live-preview", + "realtime", + "websockets", + "hibira" + ], + "homepage": "https://hibira.io", + "license": "MIT", + "authors": [ + { + "name": "Hibira", + "homepage": "https://hibira.io" + } + ], + "support": { + "issues": "https://github.com/hibira-io/statamic/issues", + "docs": "https://github.com/hibira-io/statamic#readme", + "email": "support@hibira.io" + }, + "require": { + "php": "^8.2", + "hibira-io/laravel": "^0.2", + "pusher/pusher-php-server": "^7.2", + "statamic/cms": "^5.0|^6.0" + }, + "require-dev": { + "mockery/mockery": "^1.6", + "orchestra/testbench": "^8.0|^9.0|^10.0|^11.0", + "phpunit/phpunit": "^10.0|^11.0|^12.0" + }, + "autoload": { + "psr-4": { + "Hibira\\Statamic\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Hibira\\Statamic\\Tests\\": "tests/" + } + }, + "extra": { + "statamic": { + "name": "Hibira Realtime", + "slug": "hibira-statamic", + "description": "Live comments, editing warnings and live preview on any device, over Hibira" + }, + "laravel": { + "providers": [ + "Hibira\\Statamic\\ServiceProvider" + ] + }, + "branch-alias": { + "dev-main": "0.1.x-dev" + } + }, + "scripts": { + "test": "phpunit" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pixelfear/composer-dist-plugin": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/config/hibira-statamic.php b/config/hibira-statamic.php new file mode 100644 index 0000000..ccb4ece --- /dev/null +++ b/config/hibira-statamic.php @@ -0,0 +1,61 @@ + env('HIBIRA_STATAMIC_PRESENCE', true), + + /* + |-------------------------------------------------------------------------- + | Comments + |-------------------------------------------------------------------------- + | + | Comments on entries, for everyone who may view the entry. They are + | stored as one JSON file per entry in this folder, so no database is + | needed. Commit the folder if you want comments to travel with your + | content. + | + */ + + 'comments' => [ + 'enabled' => env('HIBIRA_STATAMIC_COMMENTS', true), + 'path' => storage_path('statamic/hibira-comments'), + 'max_length' => 2000, + ], + + /* + |-------------------------------------------------------------------------- + | Live preview on other devices + |-------------------------------------------------------------------------- + | + | A live preview link opened on a phone or in another browser reloads + | when the entry is changed in the control panel. The link stays valid + | as long as Statamic's live preview token (about an hour of inactivity). + | + */ + + 'live_preview' => env('HIBIRA_STATAMIC_LIVE_PREVIEW', true), + + /* + |-------------------------------------------------------------------------- + | Statamic's own broadcasting + |-------------------------------------------------------------------------- + | + | With BROADCAST_CONNECTION=hibira, point the control panel's own Echo + | client at Hibira as well, so addons that use it (such as + | statamic/collaboration) work without more setup. + | + */ + + 'control_panel_echo' => env('HIBIRA_STATAMIC_CP_ECHO', true), + +]; diff --git a/dist/cp.js b/dist/cp.js new file mode 100644 index 0000000..1c33dd5 --- /dev/null +++ b/dist/cp.js @@ -0,0 +1,262 @@ +(()=>{var Un=Object.create;var Le=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Fn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Ee=(A,o)=>()=>(o||A((o={exports:{}}).exports,o),o.exports);var Xn=(A,o,g,P)=>{if(o&&typeof o=="object"||typeof o=="function")for(let E of zn(o))!$n.call(A,E)&&E!==g&&Le(A,E,{get:()=>o[E],enumerable:!(P=qn(o,E))||P.enumerable});return A};var Re=(A,o,g)=>(g=A!=null?Un(Fn(A)):{},Xn(o||!A||!A.__esModule?Le(g,"default",{value:A,enumerable:!0}):g,A));var Me=Ee((zt,ne)=>{(function(o,g){typeof zt=="object"&&typeof ne=="object"?ne.exports=g():typeof define=="function"&&define.amd?define([],g):typeof zt=="object"?zt.Pusher=g():o.Pusher=g()})(self,()=>(()=>{var A={594(E,L){"use strict";var z=this&&this.__extends||(function(){var M=function(S,c){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,v){b.__proto__=v}||function(b,v){for(var x in v)v.hasOwnProperty(x)&&(b[x]=v[x])},M(S,c)};return function(S,c){M(S,c);function b(){this.constructor=S}S.prototype=c===null?Object.create(c):(b.prototype=c.prototype,new b)}})();Object.defineProperty(L,"__esModule",{value:!0});var W=256,it=(function(){function M(S){S===void 0&&(S="="),this._paddingCharacter=S}return M.prototype.encodedLength=function(S){return this._paddingCharacter?(S+2)/3*4|0:(S*8+5)/6|0},M.prototype.encode=function(S){for(var c="",b=0;b>>18&63),c+=this._encodeByte(v>>>12&63),c+=this._encodeByte(v>>>6&63),c+=this._encodeByte(v>>>0&63)}var x=S.length-b;if(x>0){var v=S[b]<<16|(x===2?S[b+1]<<8:0);c+=this._encodeByte(v>>>18&63),c+=this._encodeByte(v>>>12&63),x===2?c+=this._encodeByte(v>>>6&63):c+=this._paddingCharacter||"",c+=this._paddingCharacter||""}return c},M.prototype.maxDecodedLength=function(S){return this._paddingCharacter?S/4*3|0:(S*6+7)/8|0},M.prototype.decodedLength=function(S){return this.maxDecodedLength(S.length-this._getPaddingLength(S))},M.prototype.decode=function(S){if(S.length===0)return new Uint8Array(0);for(var c=this._getPaddingLength(S),b=S.length-c,v=new Uint8Array(this.maxDecodedLength(b)),x=0,u=0,_=0,a=0,s=0,y=0,d=0;u>>4,v[x++]=s<<4|y>>>2,v[x++]=y<<6|d,_|=a&W,_|=s&W,_|=y&W,_|=d&W;if(u>>4,_|=a&W,_|=s&W),u>>2,_|=y&W),u>>8&6,c+=51-S>>>8&-75,c+=61-S>>>8&-15,c+=62-S>>>8&3,String.fromCharCode(c)},M.prototype._decodeChar=function(S){var c=W;return c+=(42-S&S-44)>>>8&-W+S-43+62,c+=(46-S&S-48)>>>8&-W+S-47+63,c+=(47-S&S-58)>>>8&-W+S-48+52,c+=(64-S&S-91)>>>8&-W+S-65+0,c+=(96-S&S-123)>>>8&-W+S-97+26,c},M.prototype._getPaddingLength=function(S){var c=0;if(this._paddingCharacter){for(var b=S.length-1;b>=0&&S[b]===this._paddingCharacter;b--)c++;if(S.length<4||c>2)throw new Error("Base64Coder: incorrect padding")}return c},M})();L.Coder=it;var ut=new it;function G(M){return ut.encode(M)}L.encode=G;function wt(M){return ut.decode(M)}L.decode=wt;var Z=(function(M){z(S,M);function S(){return M!==null&&M.apply(this,arguments)||this}return S.prototype._encodeByte=function(c){var b=c;return b+=65,b+=25-c>>>8&6,b+=51-c>>>8&-75,b+=61-c>>>8&-13,b+=62-c>>>8&49,String.fromCharCode(b)},S.prototype._decodeChar=function(c){var b=W;return b+=(44-c&c-46)>>>8&-W+c-45+62,b+=(94-c&c-96)>>>8&-W+c-95+63,b+=(47-c&c-58)>>>8&-W+c-48+52,b+=(64-c&c-91)>>>8&-W+c-65+0,b+=(96-c&c-123)>>>8&-W+c-97+26,b},S})(it);L.URLSafeCoder=Z;var K=new Z;function F(M){return K.encode(M)}L.encodeURLSafe=F;function $(M){return K.decode(M)}L.decodeURLSafe=$,L.encodedLength=function(M){return ut.encodedLength(M)},L.maxDecodedLength=function(M){return ut.maxDecodedLength(M)},L.decodedLength=function(M){return ut.decodedLength(M)}},978(E,L){"use strict";var z;z={value:!0};var W="utf8: invalid string",it="utf8: invalid source encoding";function ut(Z){for(var K=new Uint8Array(G(Z)),F=0,$=0;$>6,K[F++]=128|M&63):M<55296?(K[F++]=224|M>>12,K[F++]=128|M>>6&63,K[F++]=128|M&63):($++,M=(M&1023)<<10,M|=Z.charCodeAt($)&1023,M+=65536,K[F++]=240|M>>18,K[F++]=128|M>>12&63,K[F++]=128|M>>6&63,K[F++]=128|M&63)}return K}z=ut;function G(Z){for(var K=0,F=0;F=Z.length-1)throw new Error(W);F++,K+=4}else throw new Error(W)}return K}z=G;function wt(Z){for(var K=[],F=0;F=Z.length)throw new Error(it);var S=Z[++F];if((S&192)!==128)throw new Error(it);$=($&31)<<6|S&63,M=128}else if($<240){if(F>=Z.length-1)throw new Error(it);var S=Z[++F],c=Z[++F];if((S&192)!==128||(c&192)!==128)throw new Error(it);$=($&15)<<12|(S&63)<<6|c&63,M=2048}else if($<248){if(F>=Z.length-2)throw new Error(it);var S=Z[++F],c=Z[++F],b=Z[++F];if((S&192)!==128||(c&192)!==128||(b&192)!==128)throw new Error(it);$=($&15)<<18|(S&63)<<12|(c&63)<<6|b&63,M=65536}else throw new Error(it);if($=55296&&$<=57343)throw new Error(it);if($>=65536){if($>1114111)throw new Error(it);$-=65536,K.push(String.fromCharCode(55296|$>>10)),$=56320|$&1023}}K.push(String.fromCharCode($))}return K.join("")}L.D4=wt},721(E,L,z){E.exports=z(207).default},207(E,L,z){"use strict";z.d(L,{default:()=>Ut});class W{constructor(t,e){this.lastId=0,this.prefix=t,this.name=e}create(t){this.lastId++;var e=this.lastId,n=this.prefix+e,i=this.name+"["+e+"]",l=!1,k=function(){l||(t.apply(null,arguments),l=!0)};return this[e]=k,{number:e,id:n,name:i,callback:k}}remove(t){delete this[t.number]}}var it=new W("_pusher_script_","Pusher.ScriptReceivers"),ut={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};let G=ut;class wt{constructor(t){this.options=t,this.receivers=t.receivers||it,this.loading={}}load(t,e,n){var i=this;if(i.loading[t]&&i.loading[t].length>0)i.loading[t].push(n);else{i.loading[t]=[n];var l=j.createScriptRequest(i.getPath(t,e)),k=i.receivers.create(function(O){if(i.receivers.remove(k),i.loading[t]){var H=i.loading[t];delete i.loading[t];for(var J=function(st){st||l.cleanup()},V=0;V>>6)+N(128|t&63):N(224|t>>>12&15)+N(128|t>>>6&63)+N(128|t&63)},dt=function(r){return r.replace(/[^\x00-\x7F]/g,lt)},bt=function(r){var t=[0,2,1][r.length%3],e=r.charCodeAt(0)<<16|(r.length>1?r.charCodeAt(1):0)<<8|(r.length>2?r.charCodeAt(2):0),n=[X.charAt(e>>>18),X.charAt(e>>>12&63),t>=2?"=":X.charAt(e>>>6&63),t>=1?"=":X.charAt(e&63)];return n.join("")},$t=typeof window!="undefined"&&window.btoa||function(r){return r.replace(/[\s\S]{1,3}/g,bt)};class mt{constructor(t,e,n,i){this.clear=e,this.timer=t(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}let It=mt;function f(r){window.clearTimeout(r)}function p(r){window.clearInterval(r)}class h extends It{constructor(t,e){super(setTimeout,f,t,function(n){return e(),null})}}class m extends It{constructor(t,e){super(setInterval,p,t,function(n){return e(),n})}}var w={now(){return Date.now?Date.now():new Date().valueOf()},defer(r){return new h(0,r)},method(r,...t){var e=Array.prototype.slice.call(arguments,1);return function(n){return n[r].apply(n,e.concat(arguments))}}};let T=w;function R(r,...t){for(var e=0;e{window.console&&window.console.log&&window.console.log(t)}}debug(...t){this.log(this.globalLog,t)}warn(...t){this.log(this.globalLogWarn,t)}error(...t){this.log(this.globalLogError,t)}globalLogWarn(t){window.console&&window.console.warn?window.console.warn(t):this.globalLog(t)}globalLogError(t){window.console&&window.console.error?window.console.error(t):this.globalLogWarn(t)}log(t,...e){var n=I.apply(this,arguments);Ut.log?Ut.log(n):Ut.logToConsole&&t.bind(this)(n)}}let et=new Ge;var Qe=function(r,t,e,n,i){(e.headers!==void 0||e.headersProvider!=null)&&et.warn(`To send headers with the ${n.toString()} request, you must use AJAX, rather than JSONP.`);var l=r.nextAuthCallbackID.toString();r.nextAuthCallbackID++;var k=r.getDocument(),O=k.createElement("script");r.auth_callbacks[l]=function(V){i(null,V)};var H="Pusher.auth_callbacks['"+l+"']";O.src=e.endpoint+"?callback="+encodeURIComponent(H)+"&"+t;var J=k.getElementsByTagName("head")[0]||k.documentElement;J.insertBefore(O,J.firstChild)};let Ve=Qe;class Ye{constructor(t){this.src=t}send(t){var e=this,n="Error loading "+e.src;e.script=document.createElement("script"),e.script.id=t.id,e.script.src=e.src,e.script.type="text/javascript",e.script.charset="UTF-8",e.script.addEventListener?(e.script.onerror=function(){t.callback(n)},e.script.onload=function(){t.callback(null)}):e.script.onreadystatechange=function(){(e.script.readyState==="loaded"||e.script.readyState==="complete")&&t.callback(null)},e.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(e.errorScript=document.createElement("script"),e.errorScript.id=t.id+"_error",e.errorScript.text=t.name+"('"+n+"');",e.script.async=e.errorScript.async=!1):e.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(e.script,i.firstChild),e.errorScript&&i.insertBefore(e.errorScript,e.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Ze{constructor(t,e){this.url=t,this.data=e}send(t){if(!this.request){var e=We(this.data),n=this.url+"/"+t.number+"?"+e;this.request=j.createScriptRequest(n),this.request.send(t)}}cleanup(){this.request&&this.request.cleanup()}}var tr=function(r,t){return function(e,n){var i="http"+(t?"s":"")+"://",l=i+(r.host||r.options.host)+r.options.path,k=j.createJSONPRequest(l,e),O=j.ScriptReceivers.create(function(H,J){it.remove(O),k.cleanup(),J&&J.host&&(r.host=J.host),n&&n(H,J)});k.send(O)}},er={name:"jsonp",getAgent:tr};let rr=er;function Xt(r,t,e){var n=r+(t.useTLS?"s":""),i=t.useTLS?t.hostTLS:t.hostNonTLS;return n+"://"+i+e}function Jt(r,t){var e="/app/"+r,n="?protocol="+G.PROTOCOL+"&client=js&version="+G.VERSION+(t?"&"+t:"");return e+n}var nr={getInitial:function(r,t){var e=(t.httpPath||"")+Jt(r,"flash=false");return Xt("ws",t,e)}},ir={getInitial:function(r,t){var e=(t.httpPath||"/pusher")+Jt(r);return Xt("http",t,e)}},sr={getInitial:function(r,t){return Xt("http",t,t.httpPath||"/pusher")},getPath:function(r,t){return Jt(r)}};class or{constructor(){this._callbacks={}}get(t){return this._callbacks[Wt(t)]}add(t,e,n){var i=Wt(t);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:e,context:n})}remove(t,e,n){if(!t&&!e&&!n){this._callbacks={};return}var i=t?[Wt(t)]:D(this._callbacks);e||n?this.removeCallback(i,e,n):this.removeAllCallbacks(i)}removeCallback(t,e,n){ot(t,function(i){this._callbacks[i]=Lt(this._callbacks[i]||[],function(l){return e&&e!==l.fn||n&&n!==l.context}),this._callbacks[i].length===0&&delete this._callbacks[i]},this)}removeAllCallbacks(t){ot(t,function(e){delete this._callbacks[e]},this)}}function Wt(r){return"_"+r}class gt{constructor(t){this.callbacks=new or,this.global_callbacks=[],this.failThrough=t}bind(t,e,n){return this.callbacks.add(t,e,n),this}bind_global(t){return this.global_callbacks.push(t),this}unbind(t,e,n){return this.callbacks.remove(t,e,n),this}unbind_global(t){return t?(this.global_callbacks=Lt(this.global_callbacks||[],e=>e!==t),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(t,e,n){for(var i=0;i0)for(var i=0;i{this.onError(e),this.changeState("closed")}),!1}return this.bindListeners(),et.debug("Connecting",{transport:this.name,url:t}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(t){return this.state==="open"?(T.defer(()=>{this.socket&&this.socket.send(t)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))}onClose(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(t){this.emit("message",t)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=t=>{this.onError(t)},this.socket.onclose=t=>{this.onClose(t)},this.socket.onmessage=t=>{this.onMessage(t)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)}buildTimelineMessage(t){return R({cid:this.id},t)}}class kt{constructor(t){this.hooks=t}isSupported(t){return this.hooks.isSupported(t)}createConnection(t,e,n,i){return new ar(this.hooks,t,e,n,i)}}var hr=new kt({urls:nr,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!j.getWebSocketAPI()},isSupported:function(){return!!j.getWebSocketAPI()},getSocket:function(r){return j.createWebSocket(r)}}),ae={urls:ir,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},he=R({getSocket:function(r){return j.HTTPFactory.createStreamingSocket(r)}},ae),ce=R({getSocket:function(r){return j.HTTPFactory.createPollingSocket(r)}},ae),ue={isSupported:function(){return j.isXHRSupported()}},cr=new kt(R({},he,ue)),ur=new kt(R({},ce,ue)),lr={ws:hr,xhr_streaming:cr,xhr_polling:ur};let Nt=lr;var dr=new kt({file:"sockjs",urls:sr,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(r,t){return new window.SockJS(r,null,{js_path:K.getPath("sockjs",{useTLS:t.useTLS}),ignore_null_origin:t.ignoreNullOrigin})},beforeOpen:function(r,t){r.send(JSON.stringify({path:t}))}}),le={isSupported:function(r){var t=j.isXDRSupported(r.useTLS);return t}},fr=new kt(R({},he,le)),pr=new kt(R({},ce,le));Nt.xdr_streaming=fr,Nt.xdr_polling=pr,Nt.sockjs=dr;let gr=Nt;class vr extends gt{constructor(){super();var t=this;typeof window!="undefined"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){t.emit("online")},!1),window.addEventListener("offline",function(){t.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var br=new vr;class mr{constructor(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(t,e,n,i){i=R({},i,{activityTimeout:this.pingDelay});var l=this.transport.createConnection(t,e,n,i),k=null,O=function(){l.unbind("open",O),l.bind("closed",H),k=T.now()},H=J=>{if(l.unbind("closed",H),J.code===1002||J.code===1003)this.manager.reportDeath();else if(!J.wasClean&&k){var V=T.now()-k;V<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(V/2,this.minPingDelay))}};return l.bind("open",O),l}isSupported(t){return this.manager.isAlive()&&this.transport.isSupported(t)}}let de={decodeMessage:function(r){try{var t=JSON.parse(r.data),e=t.data;if(typeof e=="string")try{e=JSON.parse(t.data)}catch{}var n={event:t.event,channel:t.channel,data:e};return t.user_id&&(n.user_id=t.user_id),n}catch(i){throw{type:"MessageParseError",error:i,data:r.data}}},encodeMessage:function(r){return JSON.stringify(r)},processHandshake:function(r){var t=de.decodeMessage(r);if(t.event==="pusher:connection_established"){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:t.data.activity_timeout*1e3}}else{if(t.event==="pusher:error")return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"}},getCloseAction:function(r){return r.code<4e3?r.code>=1002&&r.code<=1004?"backoff":null:r.code===4e3?"tls_only":r.code<4100?"refused":r.code<4200?"backoff":r.code<4300?"retry":"refused"},getCloseError:function(r){return r.code!==1e3&&r.code!==1001?{type:"PusherError",data:{code:r.code,message:r.reason||r.message}}:null}},yt=de;class wr extends gt{constructor(t,e){super(),this.id=t,this.transport=e,this.activityTimeout=e.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(t){return this.transport.send(t)}send_event(t,e,n){var i={event:t,data:e};return n&&(i.channel=n),et.debug("Event sent",i),this.send(yt.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var t={message:n=>{var i;try{i=yt.decodeMessage(n)}catch(l){this.emit("error",{type:"MessageParseError",error:l,data:n.data})}if(i!==void 0){switch(et.debug("Event recd",i),i.event){case"pusher:error":this.emit("error",{type:"PusherError",data:i.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",i)}},activity:()=>{this.emit("activity")},error:n=>{this.emit("error",n)},closed:n=>{e(),n&&n.code&&this.handleCloseEvent(n),this.transport=null,this.emit("closed")}},e=()=>{Q(t,(n,i)=>{this.transport.unbind(i,n)})};Q(t,(n,i)=>{this.transport.bind(i,n)})}handleCloseEvent(t){var e=yt.getCloseAction(t),n=yt.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e,{action:e,error:n})}}class yr{constructor(t,e){this.transport=t,this.callback=e,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=t=>{this.unbindListeners();var e;try{e=yt.processHandshake(t)}catch(n){this.finish("error",{error:n}),this.transport.close();return}e.action==="connected"?this.finish("connected",{connection:new wr(e.id,this.transport),activityTimeout:e.activityTimeout}):(this.finish(e.action,{error:e.error}),this.transport.close())},this.onClosed=t=>{this.unbindListeners();var e=yt.getCloseAction(t)||"backoff",n=yt.getCloseError(t);this.finish(e,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(t,e){this.callback(R({transport:this.transport,action:t},e))}}class xr{constructor(t,e){this.timeline=t,this.options=e||{}}send(t,e){this.timeline.isEmpty()||this.timeline.send(j.TimelineTransport.getAgent(this,t),e)}}class Kt extends gt{constructor(t,e){super(function(n,i){et.debug("No callbacks on "+t+" for "+n)}),this.name=t,this.pusher=e,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(t,e){return e(null,{auth:""})}trigger(t,e){if(t.indexOf("client-")!==0)throw new c("Event '"+t+"' does not start with 'client-'");if(!this.subscribed){var n=M.buildLogSuffix("triggeringClientEvents");et.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(t,e,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(t){var e=t.event,n=t.data;if(e==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(t);else if(e==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(t);else if(e.indexOf("pusher_internal:")!==0){var i={};this.emit(e,n,i)}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",t.data)}handleSubscriptionCountEvent(t){t.data.subscription_count&&(this.subscriptionCount=t.data.subscription_count),this.emit("pusher:subscription_count",t.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(t,e)=>{t?(this.subscriptionPending=!1,et.error(t.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:t.message},t instanceof y?{status:t.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:e.auth,channel_data:e.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Gt extends Kt{authorize(t,e){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:t},e)}}class _r{constructor(){this.reset()}get(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null}each(t){Q(this.members,(e,n)=>{t(this.get(n))})}setMyID(t){this.myID=t}onSubscription(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)}addMember(t){return this.get(t.user_id)===null&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)}removeMember(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Cr=function(r,t,e,n){function i(l){return l instanceof e?l:new e(function(k){k(l)})}return new(e||(e=Promise))(function(l,k){function O(V){try{J(n.next(V))}catch(st){k(st)}}function H(V){try{J(n.throw(V))}catch(st){k(st)}}function J(V){V.done?l(V.value):i(V.value).then(O,H)}J((n=n.apply(r,t||[])).next())})};class Sr extends Gt{constructor(t,e){super(t,e),this.members=new _r}authorize(t,e){super.authorize(t,(n,i)=>Cr(this,void 0,void 0,function*(){if(!n)if(i=i,i.channel_data!=null){var l=JSON.parse(i.channel_data);this.members.setMyID(l.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let k=M.buildLogSuffix("authorizationEndpoint");et.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${k}, or the user should be signed in.`),e("Invalid auth response");return}e(n,i)}))}handleEvent(t){var e=t.event;if(e.indexOf("pusher_internal:")===0)this.handleInternalEvent(t);else{var n=t.data,i={};t.user_id&&(i.user_id=t.user_id),this.emit(e,n,i)}}handleInternalEvent(t){var e=t.event,n=t.data;switch(e){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(t);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(t);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var l=this.members.removeMember(n);l&&this.emit("pusher:member_removed",l);break}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(t.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Tr=z(978),Qt=z(594);class kr extends Gt{constructor(t,e,n){super(t,e),this.key=null,this.nacl=n}authorize(t,e){super.authorize(t,(n,i)=>{if(n){e(n,i);return}let l=i.shared_secret;if(!l){e(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Qt.decode)(l),delete i.shared_secret,e(null,i)})}trigger(t,e){throw new _("Client events are not currently supported for encrypted channels")}handleEvent(t){var e=t.event,n=t.data;if(e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0){super.handleEvent(t);return}this.handleEncryptedEvent(e,n)}handleEncryptedEvent(t,e){if(!this.key){et.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!e.ciphertext||!e.nonce){et.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+e);return}let n=(0,Qt.decode)(e.ciphertext);if(n.length{if(k){et.error(`Failed to make a request to the authEndpoint: ${O}. Unable to fetch new key, so dropping encrypted event`);return}if(l=this.nacl.secretbox.open(n,i,this.key),l===null){et.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(t,this.getDataToEmit(l))});return}this.emit(t,this.getDataToEmit(l))}getDataToEmit(t){let e=(0,Tr.D4)(t);try{return JSON.parse(e)}catch{return e}}}class Ar extends gt{constructor(t,e){super(),this.state="initialized",this.connection=null,this.key=t,this.options=e,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=j.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(t){this.key=t,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(t){return this.connection?this.connection.send(t):!1}send_event(t,e,n){return this.connection?this.connection.send_event(t,e,n):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var t=(e,n)=>{e?this.runner=this.strategy.connect(0,t):n.action==="error"?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,t)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var t=this.abandonConnection();t.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(t){this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new h(t||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new h(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new h(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new h(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(t){return R({},t,{message:e=>{this.resetActivityCheck(),this.emit("message",e)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:e=>{this.emit("error",e)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(t){return R({},t,{connected:e=>{this.activityTimeout=Math.min(this.options.activityTimeout,e.activityTimeout,e.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(e.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let t=e=>n=>{n.error&&this.emit("error",{type:"WebSocketError",error:n.error}),e(n)};return{tls_only:t(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:t(()=>{this.disconnect()}),backoff:t(()=>{this.retryIn(1e3)}),retry:t(()=>{this.retryIn(0)})}}setConnection(t){this.connection=t;for(var e in this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var t in this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}}updateState(t,e){var n=this.state;if(this.state=t,n!==t){var i=t;i==="connected"&&(i+=" with new socket ID "+e.socket_id),et.debug("State changed",n+" -> "+i),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Pr{constructor(){this.channels={}}add(t,e){return this.channels[t]||(this.channels[t]=Lr(t,e)),this.channels[t]}all(){return ht(this.channels)}find(t){return this.channels[t]}remove(t){var e=this.channels[t];return delete this.channels[t],e}disconnect(){Q(this.channels,function(t){t.disconnect()})}}function Lr(r,t){if(r.indexOf("private-encrypted-")===0){if(t.config.nacl)return vt.createEncryptedChannel(r,t,t.config.nacl);let e="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",n=M.buildLogSuffix("encryptedChannelSupport");throw new _(`${e}. ${n}`)}else{if(r.indexOf("private-")===0)return vt.createPrivateChannel(r,t);if(r.indexOf("presence-")===0)return vt.createPresenceChannel(r,t);if(r.indexOf("#")===0)throw new b('Cannot create a channel with name "'+r+'".');return vt.createChannel(r,t)}}var Er={createChannels(){return new Pr},createConnectionManager(r,t){return new Ar(r,t)},createChannel(r,t){return new Kt(r,t)},createPrivateChannel(r,t){return new Gt(r,t)},createPresenceChannel(r,t){return new Sr(r,t)},createEncryptedChannel(r,t,e){return new kr(r,t,e)},createTimelineSender(r,t){return new xr(r,t)},createHandshake(r,t){return new yr(r,t)},createAssistantToTheTransportManager(r,t,e){return new mr(r,t,e)}};let vt=Er;class fe{constructor(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}getAssistant(t){return vt.createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class xt{constructor(t,e){this.strategies=t,this.loop=!!e.loop,this.failFast=!!e.failFast,this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){var n=this.strategies,i=0,l=this.timeout,k=null,O=(H,J)=>{J?e(null,J):(i=i+1,this.loop&&(i=i%n.length),i0&&(l=new h(n.timeout,function(){k.abort(),i(!0)})),k=t.connect(e,function(O,H){O&&l&&l.isRunning()&&!n.failFast||(l&&l.ensureAborted(),i(O,H))}),{abort:function(){l&&l.ensureAborted(),k.abort()},forceMinPriority:function(O){k.forceMinPriority(O)}}}}class Vt{constructor(t){this.strategies=t}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){return Rr(this.strategies,t,function(n,i){return function(l,k){if(i[n].error=l,l){Mr(i)&&e(!0);return}ot(i,function(O){O.forceMinPriority(k.transport.priority)}),e(null,k)}})}}function Rr(r,t,e){var n=Pt(r,function(i,l,k,O){return i.connect(t,e(l,O))});return{abort:function(){ot(n,Or)},forceMinPriority:function(i){ot(n,function(l){l.forceMinPriority(i)})}}}function Mr(r){return Xe(r,function(t){return!!t.error})}function Or(r){!r.error&&!r.aborted&&(r.abort(),r.aborted=!0)}class Ir{constructor(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.usingTLS,i=Br(n),l=i&&i.cacheSkipCount?i.cacheSkipCount:0,k=[this.strategy];if(i&&i.timestamp+this.ttl>=T.now()){var O=this.transports[i.transport];O&&(["ws","wss"].includes(i.transport)||l>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),k.push(new xt([O],{timeout:i.latency*2+1e3,failFast:!0}))):l++)}var H=T.now(),J=k.pop().connect(t,function V(st,qt){st?(pe(n),k.length>0?(H=T.now(),J=k.pop().connect(t,V)):e(st)):(Dr(n,qt.transport.name,T.now()-H,l),e(null,qt))});return{abort:function(){J.abort()},forceMinPriority:function(V){t=V,J&&J.forceMinPriority(V)}}}}function Yt(r){return"pusherTransport"+(r?"TLS":"NonTLS")}function Br(r){var t=j.getLocalStorage();if(t)try{var e=t[Yt(r)];if(e)return JSON.parse(e)}catch{pe(r)}return null}function Dr(r,t,e,n){var i=j.getLocalStorage();if(i)try{i[Yt(r)]=Dt({timestamp:T.now(),transport:t,latency:e,cacheSkipCount:n})}catch{}}function pe(r){var t=j.getLocalStorage();if(t)try{delete t[Yt(r)]}catch{}}class Ht{constructor(t,{delay:e}){this.strategy=t,this.options={delay:e}}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy,i,l=new h(this.options.delay,function(){i=n.connect(t,e)});return{abort:function(){l.ensureAborted(),i&&i.abort()},forceMinPriority:function(k){t=k,i&&i.forceMinPriority(k)}}}}class Et{constructor(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}isSupported(){var t=this.test()?this.trueBranch:this.falseBranch;return t.isSupported()}connect(t,e){var n=this.test()?this.trueBranch:this.falseBranch;return n.connect(t,e)}}class Nr{constructor(t){this.strategy=t}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy.connect(t,function(i,l){l&&n.abort(),e(i,l)});return n}}function Rt(r){return function(){return r.isSupported()}}var Hr=function(r,t,e){var n={};function i(Ae,Dn,Nn,Hn,jn){var Pe=e(r,Ae,Dn,Nn,Hn,jn);return n[Ae]=Pe,Pe}var l=Object.assign({},t,{hostNonTLS:r.wsHost+":"+r.wsPort,hostTLS:r.wsHost+":"+r.wssPort,httpPath:r.wsPath}),k=Object.assign({},l,{useTLS:!0}),O=Object.assign({},t,{hostNonTLS:r.httpHost+":"+r.httpPort,hostTLS:r.httpHost+":"+r.httpsPort,httpPath:r.httpPath}),H={loop:!0,timeout:15e3,timeoutLimit:6e4},J=new fe({minPingDelay:1e4,maxPingDelay:r.activityTimeout}),V=new fe({lives:2,minPingDelay:1e4,maxPingDelay:r.activityTimeout}),st=i("ws","ws",3,l,J),qt=i("wss","ws",3,k,J),Rn=i("sockjs","sockjs",1,O),xe=i("xhr_streaming","xhr_streaming",1,O,V),Mn=i("xdr_streaming","xdr_streaming",1,O,V),_e=i("xhr_polling","xhr_polling",1,O),On=i("xdr_polling","xdr_polling",1,O),Ce=new xt([st],H),In=new xt([qt],H),Bn=new xt([Rn],H),Se=new xt([new Et(Rt(xe),xe,Mn)],H),Te=new xt([new Et(Rt(_e),_e,On)],H),ke=new xt([new Et(Rt(Se),new Vt([Se,new Ht(Te,{delay:4e3})]),Te)],H),ee=new Et(Rt(ke),ke,Bn),re;return t.useTLS?re=new Vt([Ce,new Ht(ee,{delay:2e3})]):re=new Vt([Ce,new Ht(In,{delay:2e3}),new Ht(ee,{delay:5e3})]),new Ir(new Nr(new Et(Rt(st),re,ee)),n,{ttl:18e5,timeline:t.timeline,useTLS:t.useTLS})};let jr=Hr;function Ur(){var r=this;r.timeline.info(r.buildTimelineMessage({transport:r.name+(r.options.useTLS?"s":"")})),r.hooks.isInitialized()?r.changeState("initialized"):r.hooks.file?(r.changeState("initializing"),K.load(r.hooks.file,{useTLS:r.options.useTLS},function(t,e){r.hooks.isInitialized()?(r.changeState("initialized"),e(!0)):(t&&r.onError(t),r.onClose(),e(!1))})):r.onClose()}var qr={getRequest:function(r){var t=new window.XDomainRequest;return t.ontimeout=function(){r.emit("error",new v),r.close()},t.onerror=function(e){r.emit("error",e),r.close()},t.onprogress=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText)},t.onload=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText),r.emit("finished",200),r.close()},t},abortRequest:function(r){r.ontimeout=r.onerror=r.onprogress=r.onload=null,r.abort()}};let zr=qr,Fr=256*1024;class $r extends gt{constructor(t,e,n){super(),this.hooks=t,this.method=e,this.url=n}start(t){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},j.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)}close(){this.unloader&&(j.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(t,e){for(;;){var n=this.advanceBuffer(e);if(n)this.emit("chunk",{status:t,data:n});else break}this.isBufferTooLong(e)&&this.emit("buffer_too_long")}advanceBuffer(t){var e=t.slice(this.position),n=e.indexOf(` +`);return n!==-1?(this.position+=n+1,e.slice(0,n)):null}isBufferTooLong(t){return this.position===t.length&&t.length>Fr}}var Zt;(function(r){r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED"})(Zt||(Zt={}));let _t=Zt;var Xr=1;class Jr{constructor(t,e){this.hooks=t,this.session=ve(1e3)+"/"+Qr(8),this.location=Wr(e),this.readyState=_t.CONNECTING,this.openStream()}send(t){return this.sendRaw(JSON.stringify([t]))}ping(){this.hooks.sendHeartbeat(this)}close(t,e){this.onClose(t,e,!0)}sendRaw(t){if(this.readyState===_t.OPEN)try{return j.createSocketRequest("POST",ge(Kr(this.location,this.session))).start(t),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(t,e,n){this.closeStream(),this.readyState=_t.CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})}onChunk(t){if(t.status===200){this.readyState===_t.OPEN&&this.onActivity();var e,n=t.data.slice(0,1);switch(n){case"o":e=JSON.parse(t.data.slice(1)||"{}"),this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var i=0;i{this.onChunk(t)}),this.stream.bind("finished",t=>{this.hooks.onFinished(this,t)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(t){T.defer(()=>{this.onError(t),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Wr(r){var t=/([^\?]*)\/*(\??.*)/.exec(r);return{base:t[1],queryString:t[2]}}function Kr(r,t){return r.base+"/"+t+"/xhr_send"}function ge(r){var t=r.indexOf("?")===-1?"?":"&";return r+t+"t="+ +new Date+"&n="+Xr++}function Gr(r,t){var e=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(r);return e[1]+t+e[3]}function ve(r){return j.randomInt(r)}function Qr(r){for(var t=[],e=0;e0&&r.onChunk(e.status,e.responseText);break;case 4:e.responseText&&e.responseText.length>0&&r.onChunk(e.status,e.responseText),r.emit("finished",e.status),r.close();break}},e},abortRequest:function(r){r.onreadystatechange=null,r.abort()}};let nn=rn;var sn={createStreamingSocket(r){return this.createSocket(Zr,r)},createPollingSocket(r){return this.createSocket(en,r)},createSocket(r,t){return new Vr(r,t)},createXHR(r,t){return this.createRequest(nn,r,t)},createRequest(r,t,e){return new $r(r,t,e)}};let be=sn;be.createXDR=function(r,t){return this.createRequest(zr,r,t)};var on={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:it,DependenciesReceivers:Z,getDefaultStrategy:jr,Transports:gr,transportConnectionInitializer:Ur,HTTPFactory:be,TimelineTransport:rr,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(r){if(typeof window!="undefined"){window.Pusher=r;var t=()=>{this.onDocumentBody(r.ready)};window.JSON?t():K.load("json2",{},t)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:C,jsonp:Ve}},onDocumentBody(r){document.body?r():setTimeout(()=>{this.onDocumentBody(r)},0)},createJSONPRequest(r,t){return new Ze(r,t)},createScriptRequest(r){return new Ye(r)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var r=this.getXHRAPI();return new r},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return br},createWebSocket(r){var t=this.getWebSocketAPI();return new t(r)},createSocketRequest(r,t){if(this.isXHRSupported())return this.HTTPFactory.createXHR(r,t);if(this.isXDRSupported(t.indexOf("https:")===0))return this.HTTPFactory.createXDR(r,t);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var r=this.getXHRAPI();return!!r&&new r().withCredentials!==void 0},isXDRSupported(r){var t=r?"https:":"http:",e=this.getProtocol();return!!window.XDomainRequest&&e===t},addUnloadListener(r){window.addEventListener!==void 0?window.addEventListener("pagehide",r,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",r)},removeUnloadListener(r){window.addEventListener!==void 0?window.removeEventListener("pagehide",r,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",r)},randomInt(r){let t=window.crypto||window.msCrypto,e=Math.floor(Math.pow(2,32)/r)*r,n;do n=t.getRandomValues(new Uint32Array(1))[0];while(n>=e);return n%r}};let j=on;var te;(function(r){r[r.ERROR=3]="ERROR",r[r.INFO=6]="INFO",r[r.DEBUG=7]="DEBUG"})(te||(te={}));let jt=te;class an{constructor(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(t,e){t<=this.options.level&&(this.events.push(R({},e,{timestamp:T.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(t){this.log(jt.ERROR,t)}info(t){this.log(jt.INFO,t)}debug(t){this.log(jt.DEBUG,t)}isEmpty(){return this.events.length===0}send(t,e){var n=R({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(n,(i,l)=>{i||this.sent++,e&&e(i,l)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class hn{constructor(t,e,n,i){this.name=t,this.priority=e,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(t,e){if(this.isSupported()){if(this.priority{n||(V(),l?l.close():i.close())},forceMinPriority:st=>{n||this.priority{var e="socket_id="+encodeURIComponent(r.socketId);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},pn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=fn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.UserAuthentication,e)}},gn=(r,t)=>{var e="socket_id="+encodeURIComponent(r.socketId);e+="&channel_name="+encodeURIComponent(r.channelName);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},vn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=gn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.ChannelAuthorization,e)}},bn=(r,t,e)=>{let n={authTransport:t.transport,authEndpoint:t.endpoint,auth:{params:t.params,headers:t.headers}};return(i,l)=>{let k=r.channel(i.channelName);e(k,n).authorize(i.socketId,l)}};function we(r,t){let e={activityTimeout:r.activityTimeout||G.activityTimeout,cluster:r.cluster,httpPath:r.httpPath||G.httpPath,httpPort:r.httpPort||G.httpPort,httpsPort:r.httpsPort||G.httpsPort,pongTimeout:r.pongTimeout||G.pongTimeout,statsHost:r.statsHost||G.stats_host,unavailableTimeout:r.unavailableTimeout||G.unavailableTimeout,wsPath:r.wsPath||G.wsPath,wsPort:r.wsPort||G.wsPort,wssPort:r.wssPort||G.wssPort,enableStats:_n(r),httpHost:mn(r),useTLS:xn(r),wsHost:wn(r),userAuthenticator:Cn(r),channelAuthorizer:Tn(r,t)};return"disabledTransports"in r&&(e.disabledTransports=r.disabledTransports),"enabledTransports"in r&&(e.enabledTransports=r.enabledTransports),"ignoreNullOrigin"in r&&(e.ignoreNullOrigin=r.ignoreNullOrigin),"timelineParams"in r&&(e.timelineParams=r.timelineParams),"nacl"in r&&(e.nacl=r.nacl),e}function mn(r){return r.httpHost?r.httpHost:r.cluster?`sockjs-${r.cluster}.pusher.com`:G.httpHost}function wn(r){return r.wsHost?r.wsHost:yn(r.cluster)}function yn(r){return`ws-${r}.pusher.com`}function xn(r){return j.getProtocol()==="https:"?!0:r.forceTLS!==!1}function _n(r){return"enableStats"in r?r.enableStats:"disableStats"in r?!r.disableStats:!1}let ye=r=>"customHandler"in r&&r.customHandler!=null;function Cn(r){let t=Object.assign(Object.assign({},G.userAuthentication),r.userAuthentication);return ye(t)?t.customHandler:pn(t)}function Sn(r,t){let e;return"channelAuthorization"in r?e=Object.assign(Object.assign({},G.channelAuthorization),r.channelAuthorization):(e={transport:r.authTransport||G.authTransport,endpoint:r.authEndpoint||G.authEndpoint},"auth"in r&&("params"in r.auth&&(e.params=r.auth.params),"headers"in r.auth&&(e.headers=r.auth.headers)),"authorizer"in r&&(e.customHandler=bn(t,e,r.authorizer))),e}function Tn(r,t){let e=Sn(r,t);return ye(e)?e.customHandler:vn(e)}class kn extends gt{constructor(t){super(function(e,n){et.debug(`No callbacks on watchlist events for ${e}`)}),this.pusher=t,this.bindWatchlistInternalEvent()}handleEvent(t){t.data.events.forEach(e=>{this.emit(e.name,e)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",t=>{var e=t.event;e==="pusher_internal:watchlist_events"&&this.handleEvent(t)})}}function An(){let r,t;return{promise:new Promise((n,i)=>{r=n,t=i}),resolve:r,reject:t}}let Pn=An;class Ln extends gt{constructor(t){super(function(e,n){et.debug("No callbacks on user for "+e)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(e,n)=>{if(e){et.warn(`Error during signin: ${e}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:e.message},e instanceof y?{status:e.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:n.auth,user_data:n.user_data})},this.pusher=t,this.pusher.connection.bind("state_change",({previous:e,current:n})=>{e!=="connected"&&n==="connected"&&this._signin(),e==="connected"&&n!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new kn(t),this.pusher.connection.bind("message",e=>{var n=e.event;n==="pusher:signin_success"&&this._onSigninSuccess(e.data),this.serverToUserChannel&&this.serverToUserChannel.name===e.channel&&this.serverToUserChannel.handleEvent(e)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(t){try{this.user_data=JSON.parse(t.user_data)}catch{et.error(`Failed parsing user data after signin: ${t.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){et.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){let t=e=>{e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.pusher.connection.state==="connected"&&e.subscribe()};this.serverToUserChannel=new Kt(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((e,n)=>{e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0||this.emit(e,n)}),t(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;let{promise:t,resolve:e,reject:n}=Pn();t.done=!1;let i=()=>{t.done=!0};t.then(i).catch(i),this.signinDonePromise=t,this._signinDoneResolve=e}}class at{static ready(){at.isReady=!0;for(var t=0,e=at.instances.length;tj.getDefaultStrategy(this.config,i,un);this.connection=vt.createConnectionManager(this.key,{getStrategy:n,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",i=>{var l=i.event,k=l.indexOf("pusher_internal:")===0;if(i.channel){var O=this.channel(i.channel);O&&O.handleEvent(i)}k||this.global_emitter.emit(i.event,i.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",i=>{et.warn(i)}),at.instances.push(this),this.timeline.info({instances:at.instances.length}),this.user=new Ln(this),at.isReady&&this.connect()}switchCluster(t){let{appKey:e,cluster:n}=t;this.key=e,this.options=Object.assign(Object.assign({},this.options),{cluster:n}),this.config=we(this.options,this),this.connection.switchCluster(this.key)}channel(t){return this.channels.find(t)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var t=this.connection.isUsingTLS(),e=this.timelineSender;this.timelineSenderTimer=new m(6e4,function(){e.send(t)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(t,e,n){return this.global_emitter.bind(t,e,n),this}unbind(t,e,n){return this.global_emitter.unbind(t,e,n),this}bind_global(t){return this.global_emitter.bind_global(t),this}unbind_global(t){return this.global_emitter.unbind_global(t),this}unbind_all(t){return this.global_emitter.unbind_all(),this}subscribeAll(){var t;for(t in this.channels.channels)this.channels.channels.hasOwnProperty(t)&&this.subscribe(t)}subscribe(t){var e=this.channels.add(t,this);return e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.connection.state==="connected"&&e.subscribe(),e}unsubscribe(t){var e=this.channels.find(t);e&&e.subscriptionPending?e.cancelSubscription():(e=this.channels.remove(t),e&&e.subscribed&&e.unsubscribe())}send_event(t,e,n){return this.connection.send_event(t,e,n)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}at.instances=[],at.isReady=!1,at.logToConsole=!1,at.Runtime=j,at.ScriptReceivers=j.ScriptReceivers,at.DependenciesReceivers=j.DependenciesReceivers,at.auth_callbacks=j.auth_callbacks;let Ut=at;function En(r){if(r==null)throw"You must pass your app key when you instantiate Pusher."}j.setup(at)}},o={};function g(E){var L=o[E];if(L!==void 0)return L.exports;var z=o[E]={exports:{}};return A[E].call(z.exports,z,z.exports,g),z.exports}g.d=(E,L)=>{for(var z in L)g.o(L,z)&&!g.o(E,z)&&Object.defineProperty(E,z,{enumerable:!0,get:L[z]})},g.o=(E,L)=>Object.prototype.hasOwnProperty.call(E,L);var P=g(721);return P})())});var De=Ee((Ie,Be)=>{var Oe=(function(){var A=function(c,b){var v=236,x=17,u=c,_=g[b],a=null,s=0,y=null,d=[],C={},U=function(f,p){s=u*4+17,a=(function(h){for(var m=new Array(h),w=0;w=7&&ct(f),y==null&&(y=$t(u,_,d)),dt(y,p)},N=function(f,p){for(var h=-1;h<=7;h+=1)if(!(f+h<=-1||s<=f+h))for(var m=-1;m<=7;m+=1)p+m<=-1||s<=p+m||(0<=h&&h<=6&&(m==0||m==6)||0<=m&&m<=6&&(h==0||h==6)||2<=h&&h<=4&&2<=m&&m<=4?a[f+h][p+m]=!0:a[f+h][p+m]=!1)},X=function(){for(var f=0,p=0,h=0;h<8;h+=1){U(!0,h);var m=E.getLostPoint(C);(h==0||f>m)&&(f=m,p=h)}return p},rt=function(){for(var f=8;f>h&1)==1;a[Math.floor(h/3)][h%3+s-8-3]=m}for(var h=0;h<18;h+=1){var m=!f&&(p>>h&1)==1;a[h%3+s-8-3][Math.floor(h/3)]=m}},lt=function(f,p){for(var h=_<<3|p,m=E.getBCHTypeInfo(h),w=0;w<15;w+=1){var T=!f&&(m>>w&1)==1;w<6?a[w][8]=T:w<8?a[w+1][8]=T:a[s-15+w][8]=T}for(var w=0;w<15;w+=1){var T=!f&&(m>>w&1)==1;w<8?a[8][s-w-1]=T:w<9?a[8][15-w-1+1]=T:a[8][15-w-1]=T}a[s-8][8]=!f},dt=function(f,p){for(var h=-1,m=s-1,w=7,T=0,R=E.getMaskFunction(p),I=s-1;I>0;I-=2)for(I==6&&(I-=1);;){for(var tt=0;tt<2;tt+=1)if(a[m][I-tt]==null){var Q=!1;T>>w&1)==1);var D=R(m,I-tt);D&&(Q=!Q),a[m][I-tt]=Q,w-=1,w==-1&&(T+=1,w=7)}if(m+=h,m<0||s<=m){m-=h,h=-h;break}}},bt=function(f,p){for(var h=0,m=0,w=0,T=new Array(p.length),R=new Array(p.length),I=0;I=0?Pt.getAt(Bt):0}}for(var Lt=0,D=0;DI*8)throw"code length overflow. ("+w.getLengthInBits()+">"+I*8+")";for(w.getLengthInBits()+4<=I*8&&w.put(0,4);w.getLengthInBits()%8!=0;)w.putBit(!1);for(;!(w.getLengthInBits()>=I*8||(w.put(v,8),w.getLengthInBits()>=I*8));)w.put(x,8);return bt(w,m)};C.addData=function(f,p){p=p||"Byte";var h=null;switch(p){case"Numeric":h=ut(f);break;case"Alphanumeric":h=G(f);break;case"Byte":h=wt(f);break;case"Kanji":h=Z(f);break;default:throw"mode:"+p}d.push(h),y=null},C.isDark=function(f,p){if(f<0||s<=f||p<0||s<=p)throw f+","+p;return a[f][p]},C.getModuleCount=function(){return s},C.make=function(){if(u<1){for(var f=1;f<40;f++){for(var p=W.getRSBlocks(f,_),h=it(),m=0;m";for(var w=0;w';h+=""}return h+="",h+="",h},C.createSvgTag=function(f,p,h,m){var w={};typeof arguments[0]=="object"&&(w=arguments[0],f=w.cellSize,p=w.margin,h=w.alt,m=w.title),f=f||2,p=typeof p=="undefined"?f*4:p,h=typeof h=="string"?{text:h}:h||{},h.text=h.text||null,h.id=h.text?h.id||"qrcode-description":null,m=typeof m=="string"?{text:m}:m||{},m.text=m.text||null,m.id=m.text?m.id||"qrcode-title":null;var T=C.getModuleCount()*f+p*2,R,I,tt,Q,D="",ht;for(ht="l"+f+",0 0,"+f+" -"+f+",0 0,-"+f+"z ",D+=''+mt(m.text)+"":"",D+=h.text?''+mt(h.text)+"":"",D+='',D+='":p+=">";break;case"&":p+="&";break;case'"':p+=""";break;default:p+=m;break}}return p},It=function(f){var p=1;f=typeof f=="undefined"?p*2:f;var h=C.getModuleCount()*p+f*2,m=f,w=h-f,T,R,I,tt,Q,D={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},ht={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},ot="";for(T=0;T=w?ht[Q]:D[Q];ot+=` +`}return h%2&&f>0?ot.substring(0,ot.length-h-1)+Array(h+1).join("\u2580"):ot.substring(0,ot.length-1)};return C.createASCII=function(f,p){if(f=f||1,f<2)return It(p);f-=1,p=typeof p=="undefined"?f*2:p;var h=C.getModuleCount()*f+p*2,m=p,w=h-p,T,R,I,tt,Q=Array(f+1).join("\u2588\u2588"),D=Array(f+1).join(" "),ht="",ot="";for(T=0;T>>8),_.push(y&255)):_.push(x)}}return _}};var o={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},g={L:1,M:0,Q:3,H:2},P={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},E=(function(){var c=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],b=1335,v=7973,x=21522,u={},_=function(a){for(var s=0;a!=0;)s+=1,a>>>=1;return s};return u.getBCHTypeInfo=function(a){for(var s=a<<10;_(s)-_(b)>=0;)s^=b<<_(s)-_(b);return(a<<10|s)^x},u.getBCHTypeNumber=function(a){for(var s=a<<12;_(s)-_(v)>=0;)s^=v<<_(s)-_(v);return a<<12|s},u.getPatternPosition=function(a){return c[a-1]},u.getMaskFunction=function(a){switch(a){case P.PATTERN000:return function(s,y){return(s+y)%2==0};case P.PATTERN001:return function(s,y){return s%2==0};case P.PATTERN010:return function(s,y){return y%3==0};case P.PATTERN011:return function(s,y){return(s+y)%3==0};case P.PATTERN100:return function(s,y){return(Math.floor(s/2)+Math.floor(y/3))%2==0};case P.PATTERN101:return function(s,y){return s*y%2+s*y%3==0};case P.PATTERN110:return function(s,y){return(s*y%2+s*y%3)%2==0};case P.PATTERN111:return function(s,y){return(s*y%3+(s+y)%2)%2==0};default:throw"bad maskPattern:"+a}},u.getErrorCorrectPolynomial=function(a){for(var s=z([1],0),y=0;y5&&(y+=3+U-5)}for(var d=0;d=256;)u-=255;return c[u]},x})();function z(c,b){if(typeof c.length=="undefined")throw c.length+"/"+b;var v=(function(){for(var u=0;u>>7-x%8&1)==1},v.put=function(x,u){for(var _=0;_>>u-_-1&1)==1)},v.getLengthInBits=function(){return b},v.putBit=function(x){var u=Math.floor(b/8);c.length<=u&&c.push(0),x&&(c[u]|=128>>>b%8),b+=1},v},ut=function(c){var b=o.MODE_NUMBER,v=c,x={};x.getMode=function(){return b},x.getLength=function(a){return v.length},x.write=function(a){for(var s=v,y=0;y+2>>8&255)*192+(d&255),a.put(d,13),y+=2}if(y>>8)},b.writeBytes=function(v,x,u){x=x||0,u=u||v.length;for(var _=0;_0&&(v+=","),v+=c[x];return v+="]",v},b},F=function(){var c=0,b=0,v=0,x="",u={},_=function(s){x+=String.fromCharCode(a(s&63))},a=function(s){if(!(s<0)){if(s<26)return 65+s;if(s<52)return 97+(s-26);if(s<62)return 48+(s-52);if(s==62)return 43;if(s==63)return 47}throw"n:"+s};return u.writeByte=function(s){for(c=c<<8|s&255,b+=8,v+=1;b>=6;)_(c>>>b-6),b-=6},u.flush=function(){if(b>0&&(_(c<<6-b),c=0,b=0),v%3!=0)for(var s=3-v%3,y=0;y=b.length){if(u==0)return-1;throw"unexpected end of file./"+u}var s=b.charAt(v);if(v+=1,s=="=")return u=0,-1;if(s.match(/^\s$/))continue;x=x<<6|a(s.charCodeAt(0)),u+=6}var y=x>>>u-8&255;return u-=8,y};var a=function(s){if(65<=s&&s<=90)return s-65;if(97<=s&&s<=122)return s-97+26;if(48<=s&&s<=57)return s-48+52;if(s==43)return 62;if(s==47)return 63;throw"c:"+s};return _},M=function(c,b){var v=c,x=b,u=new Array(c*b),_={};_.setPixel=function(d,C,U){u[C*v+d]=U},_.write=function(d){d.writeString("GIF87a"),d.writeShort(v),d.writeShort(x),d.writeByte(128),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(255),d.writeByte(255),d.writeByte(255),d.writeString(","),d.writeShort(0),d.writeShort(0),d.writeShort(v),d.writeShort(x),d.writeByte(0);var C=2,U=s(C);d.writeByte(C);for(var N=0;U.length-N>255;)d.writeByte(255),d.writeBytes(U,N,255),N+=255;d.writeByte(U.length-N),d.writeBytes(U,N,U.length-N),d.writeByte(0),d.writeString(";")};var a=function(d){var C=d,U=0,N=0,X={};return X.write=function(rt,nt){if(rt>>>nt)throw"length over";for(;U+nt>=8;)C.writeByte(255&(rt<>>=8-U,N=0,U=0;N=rt<0&&C.writeByte(N)},X},s=function(d){for(var C=1<>6,128|L&63):L<55296||L>=57344?P.push(224|L>>12,128|L>>6&63,128|L&63):(E++,L=65536+((L&1023)<<10|g.charCodeAt(E)&1023),P.push(240|L>>18,128|L>>12&63,128|L>>6&63,128|L&63))}return P}return o(A)}})();(function(A){typeof define=="function"&&define.amd?define([],A):typeof Ie=="object"&&(Be.exports=A())})(function(){return Oe})});var ze=Re(Me()),Fe=Re(De());var Ne=`.hibira-st { + --h-bg: #ffffff; + --h-fg: #1f2937; + --h-muted: #6b7280; + --h-border: #e5e7eb; + --h-soft: #f3f4f6; + --h-accent: #4f46e5; + --h-accent-fg: #ffffff; + --h-warn-bg: #fffbeb; + --h-warn-fg: #92400e; + --h-warn-border: #fcd34d; + --h-danger: #dc2626; + --h-shadow: 0 10px 30px rgba(15, 23, 42, .16), 0 2px 6px rgba(15, 23, 42, .08); + position: fixed; + right: 16px; + bottom: 16px; + z-index: 40; + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 8px; + max-width: calc(100vw - 32px); + font-family: inherit; + font-size: 14px; + line-height: 1.4; + color: var(--h-fg); +} +.hibira-st.hibira-st-dark { + --h-bg: #1f2125; + --h-fg: #e5e7eb; + --h-muted: #9ca3af; + --h-border: #374151; + --h-soft: #2b2e33; + --h-accent: #818cf8; + --h-accent-fg: #111827; + --h-warn-bg: #3a2e12; + --h-warn-fg: #fde68a; + --h-warn-border: #a16207; + --h-danger: #f87171; + --h-shadow: 0 10px 30px rgba(0, 0, 0, .5); +} +.hibira-st *, .hibira-st *::before, .hibira-st *::after { box-sizing: border-box; } +.hibira-st button { + font: inherit; + color: inherit; + background: none; + border: 0; + margin: 0; + padding: 0; + cursor: pointer; +} +.hibira-st button:focus-visible, .hibira-st textarea:focus-visible { + outline: 2px solid var(--h-accent); + outline-offset: 2px; +} +.hibira-st svg { display: block; } + +.hibira-st-dock { + display: flex; + align-items: center; + gap: 4px; + padding: 4px; + background: var(--h-bg); + border: 1px solid var(--h-border); + border-radius: 999px; + box-shadow: var(--h-shadow); +} +.hibira-st-people { display: flex; align-items: center; gap: 8px; padding: 0 6px 0 2px; } +.hibira-st-people[hidden] { display: none; } +.hibira-st-avatars { display: flex; } +.hibira-st-avatars > * + * { margin-left: -8px; } +.hibira-st-label { color: var(--h-muted); font-size: 13px; white-space: nowrap; max-width: 240px; overflow: hidden; text-overflow: ellipsis; } +.hibira-st-sep { width: 1px; height: 20px; background: var(--h-border); margin: 0 2px; } +.hibira-st-sep[hidden] { display: none; } + +.hibira-st-avatar { + position: relative; + flex: none; + width: 28px; + height: 28px; + border-radius: 999px; + border: 2px solid var(--h-bg); + color: #fff; + font-size: 11px; + font-weight: 600; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + background: var(--h-muted); +} +.hibira-st-avatar img { width: 100%; height: 100%; object-fit: cover; } +.hibira-st-avatar.hibira-st-more { background: var(--h-soft); color: var(--h-fg); } + +.hibira-st-icon { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 32px; + height: 32px; + padding: 0 8px; + border-radius: 999px; + color: var(--h-muted); +} +.hibira-st-icon:hover, .hibira-st-icon[aria-expanded="true"] { background: var(--h-soft); color: var(--h-fg); } +.hibira-st-icon.hibira-st-sm { min-width: 28px; height: 28px; padding: 0 6px; } +.hibira-st-count { font-size: 12px; font-weight: 600; } +.hibira-st-count:empty { display: none; } +.hibira-st-new .hibira-st-count { + background: var(--h-accent); + color: var(--h-accent-fg); + border-radius: 999px; + padding: 0 6px; +} + +[data-tip]:hover::after, [data-tip]:focus-visible::after { + content: attr(data-tip); + position: absolute; + bottom: calc(100% + 8px); + right: 0; + padding: 4px 8px; + border-radius: 6px; + background: #111827; + color: #f9fafb; + font-size: 12px; + font-weight: 400; + white-space: nowrap; + pointer-events: none; + z-index: 1; +} + +.hibira-st-status { width: 8px; height: 8px; border-radius: 999px; background: #d1d5db; margin: 0 8px 0 4px; } +.hibira-st-status[data-state="connected"] { background: #22c55e; } +.hibira-st-status[data-state="connecting"], .hibira-st-status[data-state="unavailable"] { background: #f59e0b; } + +.hibira-st-card { + width: 360px; + max-width: 100%; + background: var(--h-bg); + border: 1px solid var(--h-border); + border-radius: 12px; + box-shadow: var(--h-shadow); + overflow: hidden; +} +.hibira-st-card[hidden], .hibira-st-banner[hidden] { display: none; } +.hibira-st-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 8px 10px 14px; + border-bottom: 1px solid var(--h-border); + font-weight: 600; +} +.hibira-st-head-actions { display: flex; align-items: center; gap: 2px; } +.hibira-st-text-button { font-size: 12px; font-weight: 500; color: var(--h-muted); padding: 4px 8px; border-radius: 6px; } +.hibira-st-text-button:hover { background: var(--h-soft); color: var(--h-fg); } +.hibira-st-list { max-height: min(55vh, 460px); overflow-y: auto; padding: 4px 0; } +.hibira-st-empty { padding: 20px 16px; color: var(--h-muted); text-align: center; } +.hibira-st-comment { display: flex; gap: 10px; padding: 10px 14px; } +.hibira-st-comment + .hibira-st-comment { border-top: 1px solid var(--h-soft); } +.hibira-st-comment.hibira-st-resolved { opacity: .65; } +.hibira-st-comment-main { flex: 1; min-width: 0; } +.hibira-st-comment-meta { display: flex; align-items: baseline; gap: 6px; } +.hibira-st-comment-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.hibira-st-comment-time { color: var(--h-muted); font-size: 12px; white-space: nowrap; } +.hibira-st-comment-actions { margin-left: auto; display: flex; gap: 0; opacity: 0; transition: opacity .1s; } +.hibira-st-comment:hover .hibira-st-comment-actions, .hibira-st-comment:focus-within .hibira-st-comment-actions { opacity: 1; } +@media (hover: none) { .hibira-st-comment-actions { opacity: 1; } } +.hibira-st-comment-body { white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 2px; } +.hibira-st-comment-note { color: var(--h-muted); font-size: 12px; margin-top: 4px; } +.hibira-st-confirm { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 13px; } +.hibira-st-danger { color: var(--h-danger) !important; font-weight: 600; } +.hibira-st-comment .hibira-st-avatar { width: 28px; height: 28px; border: 0; } + +.hibira-st-compose { border-top: 1px solid var(--h-border); padding: 10px; display: flex; gap: 8px; align-items: flex-end; } +.hibira-st-compose textarea { + flex: 1; + min-height: 38px; + max-height: 160px; + resize: none; + padding: 8px 10px; + border: 1px solid var(--h-border); + border-radius: 8px; + background: var(--h-bg); + color: var(--h-fg); + font: inherit; + line-height: 1.4; +} +.hibira-st-compose textarea::placeholder { color: var(--h-muted); } +.hibira-st-send { + flex: none; + width: 38px; + height: 38px; + border-radius: 8px !important; + background: var(--h-accent) !important; + color: var(--h-accent-fg) !important; + display: flex; + align-items: center; + justify-content: center; +} +.hibira-st-send:disabled { opacity: .5; cursor: default; } +.hibira-st-error { color: var(--h-danger); font-size: 12px; padding: 0 12px 8px; } +.hibira-st-error:empty { display: none; } + +.hibira-st-preview { padding: 14px; display: flex; flex-direction: column; gap: 12px; } +.hibira-st-qr { align-self: center; width: 184px; height: 184px; padding: 8px; background: #fff; border-radius: 8px; } +.hibira-st-qr svg { width: 100%; height: 100%; } +.hibira-st-link { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + padding: 8px; + background: var(--h-soft); + border-radius: 6px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.hibira-st-hint { color: var(--h-muted); font-size: 13px; } +.hibira-st-row { display: flex; gap: 8px; } +.hibira-st-button { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px !important; + border: 1px solid var(--h-border) !important; + border-radius: 8px !important; + font-size: 13px !important; + font-weight: 500 !important; + text-decoration: none; + color: var(--h-fg); + background: var(--h-bg); +} +.hibira-st-button:hover { background: var(--h-soft) !important; } +.hibira-st-button.hibira-st-primary { background: var(--h-accent) !important; border-color: var(--h-accent) !important; color: var(--h-accent-fg) !important; } + +.hibira-st-banner { + width: 360px; + max-width: 100%; + display: flex; + gap: 10px; + align-items: flex-start; + padding: 12px 14px; + border: 1px solid var(--h-warn-border); + background: var(--h-warn-bg); + color: var(--h-warn-fg); + border-radius: 12px; + box-shadow: var(--h-shadow); +} +.hibira-st-banner-text { flex: 1; } +.hibira-st-banner .hibira-st-row { margin-top: 8px; } +.hibira-st-banner .hibira-st-button { border-color: var(--h-warn-border) !important; background: transparent; color: inherit; } + +@media (max-width: 640px) { + .hibira-st { right: 8px; bottom: 8px; max-width: calc(100vw - 16px); } + .hibira-st-label { display: none; } +} +`;var He=document.currentScript,$e=He?He.src.replace(/cp\.js(\?.*)?$/,""):null,Wn=/\/collections\/[^/]+\/entries\/([A-Za-z0-9_-]{1,100})\/?$/,Kn=["create","actions","reorder"],ie=null,Y=null,ft=null,pt=null;function q(A,o={}){let g=Y&&Y.strings&&Y.strings[A]||A;for(let[P,E]of Object.entries(o))g=g.split(":"+P).join(String(E));return g}function B(A,o={},...g){let P=document.createElement(A);for(let[E,L]of Object.entries(o))L==null||L===!1||(E==="class"?P.className=L:E.startsWith("on")?P.addEventListener(E.slice(2),L):P.setAttribute(E,L===!0?"":L));for(let E of g.flat())E==null||E===!1||P.append(E instanceof Node?E:document.createTextNode(String(E)));return P}var Gn={comment:'',phone:'',close:'',check:'',undo:'',trash:'',send:'',copy:'',open:'',warn:''};function Ot(A,o=18){let g=document.createElement("span");return g.innerHTML=``,g.firstChild}function At(A,o,g,P=""){return B("button",{type:"button",class:"hibira-st-icon "+P,"aria-label":o,"data-tip":o,onclick:g},Ot(A))}function je(A){let o=B("span",{class:"hibira-st-avatar",style:`background:${A.color||"#6b7280"}`});if(A.avatar){let g=B("img",{src:A.avatar,alt:""});g.addEventListener("error",()=>g.replaceWith(document.createTextNode(A.initials||"?"))),o.append(g)}else o.append(A.initials||"?");return o}function Qn(A){let o=Math.round((new Date(A).getTime()-Date.now())/1e3);try{let g=new Intl.RelativeTimeFormat(Y.locale,{numeric:"auto"}),P=[[60,"second"],[3600,"minute",60],[86400,"hour",3600],[604800,"day",86400]];if(Math.abs(o)<45)return g.format(0,"second");for(let[E,L,z=1]of P)if(Math.abs(o)Y=A).catch(()=>Y={enabled:!1})),ie}function Zn(){if(ft)return ft;let A=Y.connection;return ft=new ze.default(A.key,{cluster:"hkg",wsHost:A.host,wsPort:A.port,wssPort:A.port,forceTLS:A.tls,enabledTransports:["ws","wss"],disableStats:!0,channelAuthorization:{customHandler:({socketId:o,channelName:g},P)=>{Ct(Y.routes.auth,{method:"POST",body:{socket_id:o,channel_name:g}}).then(E=>P(null,E)).catch(E=>P(E,null))}}}),ft.connection.bind("state_change",({current:o})=>pt&&pt.setState(o)),ft}var se=class{constructor(o){this.entryId=o,this.channelName="presence-hibira-statamic.entry."+o,this.comments=[],this.loaded=!1,this.showResolved=!1,this.open=null,this.unread=!1,this.subscribed=!1,this.confirming=null,this.build(),this.subscribe(),Y.features.comments&&this.loadComments()}build(){let o=Y.features;this.avatars=B("span",{class:"hibira-st-avatars"}),this.label=B("span",{class:"hibira-st-label"}),this.people=B("span",{class:"hibira-st-people",hidden:!0},this.avatars,this.label),this.separator=B("span",{class:"hibira-st-sep",hidden:!0}),this.status=B("span",{class:"hibira-st-status","data-state":"connecting"}),this.commentsButton=o.comments?At("comment",q("comments"),()=>this.toggle("comments")):null,this.commentsButton&&(this.count=B("span",{class:"hibira-st-count"}),this.commentsButton.append(this.count),this.commentsButton.setAttribute("aria-expanded","false")),this.previewButton=o.livePreview?At("phone",q("preview"),()=>this.toggle("preview")):null,this.previewButton&&this.previewButton.setAttribute("aria-expanded","false"),this.dock=B("div",{class:"hibira-st-dock"},this.people,this.separator,this.commentsButton,this.previewButton,this.status),this.banner=B("div",{class:"hibira-st-banner",role:"status",hidden:!0}),this.card=B("div",{class:"hibira-st-card",hidden:!0}),this.root=B("div",{class:"hibira-st"},this.banner,this.card,this.dock),this.applyTheme(),this.themeObserver=new MutationObserver(()=>this.applyTheme()),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),this.onKey=g=>{g.key==="Escape"&&this.open&&this.toggle(null)},document.addEventListener("keydown",this.onKey),document.body.append(this.root)}applyTheme(){this.root.classList.toggle("hibira-st-dark",Vn())}setState(o){this.status.dataset.state=o;let g=o==="connected"?"Hibira":q("reconnecting");this.status.setAttribute("title",g)}toggle(o){this.open=this.open===o?null:o,this.commentsButton&&this.commentsButton.setAttribute("aria-expanded",String(this.open==="comments")),this.previewButton&&this.previewButton.setAttribute("aria-expanded",String(this.open==="preview")),this.card.hidden=!this.open,this.open==="comments"?(this.unread=!1,this.renderCount(),this.renderComments(),setTimeout(()=>this.textarea.focus(),0)):this.open==="preview"&&this.renderPreview()}head(o,...g){return B("div",{class:"hibira-st-head"},B("span",{},o),B("span",{class:"hibira-st-head-actions"},...g,At("close",q("close"),()=>this.toggle(null),"hibira-st-sm")))}subscribe(){this.setState(Zn().connection.state),this.channel=ft.subscribe(this.channelName),this.channel.bind("pusher:subscription_succeeded",()=>{this.subscribed&&Y.features.comments&&this.loadComments(),this.subscribed=!0,this.renderPeople()}),this.channel.bind("pusher:member_added",()=>this.renderPeople()),this.channel.bind("pusher:member_removed",()=>this.renderPeople()),this.channel.bind("saved",o=>this.onSaved(o)),this.channel.bind("comment",o=>this.onComment(o))}others(){let o=[];return!this.channel||!this.channel.members||this.channel.members.each(g=>{String(g.id)!==String(Y.user.id)&&o.push({id:g.id,...g.info})}),o}renderPeople(){if(!Y.features.presence)return;let o=this.others();this.people.hidden=o.length===0,this.separator.hidden=o.length===0||!this.commentsButton&&!this.previewButton,this.avatars.replaceChildren(...o.slice(0,3).map(g=>{let P=je(g);return P.setAttribute("data-tip",g.name),P.setAttribute("aria-label",g.name),P})),o.length>3&&this.avatars.append(B("span",{class:"hibira-st-avatar hibira-st-more"},"+"+(o.length-3))),this.label.textContent=o.length===0?"":o.length===1?q("here_one",{name:o[0].name}):q("here_many",{name:o[0].name,count:o.length-1})}onSaved(o){if(!Y.features.presence||o&&o.by&&String(o.by.id)===String(Y.user.id))return;let g=o&&o.by?q("saved_by",{name:o.by.name}):q("saved_elsewhere");this.banner.replaceChildren(B("span",{style:"flex:none;margin-top:1px"},Ot("warn",18)),B("div",{class:"hibira-st-banner-text"},g,B("div",{class:"hibira-st-row"},B("button",{type:"button",class:"hibira-st-button",onclick:()=>location.reload()},q("reload")),B("button",{type:"button",class:"hibira-st-button",onclick:()=>this.banner.hidden=!0},q("dismiss"))))),this.banner.hidden=!1}async loadComments(){try{let o=await Ct(Mt("comments",this.entryId));this.comments=o.comments||[],this.loaded=!0,this.renderCount(),this.open==="comments"&&this.renderComments()}catch{}}onComment({action:o,comment:g}){o==="added"?(this.comments.some(P=>P.id===g.id)||this.comments.push(g),this.open!=="comments"&&String(g.author.id)!==String(Y.user.id)&&(this.unread=!0)):o==="updated"?this.comments=this.comments.map(P=>P.id===g.id?g:P):o==="deleted"&&(this.comments=this.comments.filter(P=>P.id!==g.id)),this.renderCount(),this.open==="comments"&&this.renderComments()}open_(){return this.comments.filter(o=>!o.resolved_at)}renderCount(){if(!this.commentsButton)return;let o=this.open_().length;this.count.textContent=o?String(o):"",this.commentsButton.classList.toggle("hibira-st-new",this.unread);let g=o?q("comments_count",{count:o}):q("comments");this.commentsButton.setAttribute("aria-label",g),this.commentsButton.setAttribute("data-tip",this.unread?g+" \u2022":g)}renderComments(){(!this.compose||!this.card.contains(this.compose))&&this.buildCommentsCard();let o=this.comments.filter(z=>z.resolved_at),g=this.showResolved?this.comments:this.open_();this.resolvedToggle.hidden=o.length===0,this.resolvedToggle.textContent=this.showResolved?q("hide_resolved"):q("show_resolved",{count:o.length});let P=this.list,E=P.scrollTop+P.clientHeight>=P.scrollHeight-8,L=P.scrollTop;P.replaceChildren(...g.length?g.map(z=>this.renderComment(z)):[B("div",{class:"hibira-st-empty"},this.loaded?q("empty"):"\u2026")]),P.scrollTop=E?P.scrollHeight:L}buildCommentsCard(){this.resolvedToggle=B("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.showResolved=!this.showResolved,this.renderComments()}}),this.list=B("div",{class:"hibira-st-list"}),this.textarea=B("textarea",{rows:1,placeholder:q("placeholder"),"aria-label":q("placeholder"),maxlength:Y.maxLength,oninput:()=>this.resize(),onkeydown:o=>{o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&(o.preventDefault(),this.send())}}),this.sendButton=B("button",{type:"button",class:"hibira-st-send","aria-label":q("send"),"data-tip":q("send_hint"),onclick:()=>this.send()},Ot("send",18)),this.error=B("div",{class:"hibira-st-error",role:"alert"}),this.compose=B("div",{class:"hibira-st-compose"},this.textarea,this.sendButton),this.card.replaceChildren(this.head(q("comments"),this.resolvedToggle),this.list,this.compose,this.error),this.resize()}renderComment(o){let g=String(o.author.id)===String(Y.user.id),P=g||Y.user.super,E=B("span",{class:"hibira-st-comment-actions"},o.resolved_at?At("undo",q("reopen"),()=>this.resolve(o,!1),"hibira-st-sm"):At("check",q("resolve"),()=>this.resolve(o,!0),"hibira-st-sm"),P?At("trash",q("delete"),()=>{this.confirming=o.id,this.renderComments()},"hibira-st-sm"):null),L=this.confirming===o.id?B("div",{class:"hibira-st-confirm"},B("span",{},q("delete_confirm")),B("button",{type:"button",class:"hibira-st-text-button hibira-st-danger",onclick:()=>this.remove(o)},q("delete")),B("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.confirming=null,this.renderComments()}},q("dismiss"))):null;return B("div",{class:"hibira-st-comment"+(o.resolved_at?" hibira-st-resolved":"")},je(o.author),B("div",{class:"hibira-st-comment-main"},B("div",{class:"hibira-st-comment-meta"},B("span",{class:"hibira-st-comment-name"},g?q("you"):o.author.name),B("time",{class:"hibira-st-comment-time",datetime:o.created_at,title:new Date(o.created_at).toLocaleString(Y.locale)},Qn(o.created_at)),E),B("div",{class:"hibira-st-comment-body"},o.body),o.resolved_by?B("div",{class:"hibira-st-comment-note"},q("resolved_by",{name:o.resolved_by.name})):null,L))}resize(){this.textarea&&(this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight+2,160)+"px",this.sendButton.disabled=this.textarea.value.trim()==="")}async send(){let o=this.textarea.value.trim();if(!(!o||this.sending)){if(o.length>Y.maxLength){this.error.textContent=q("too_long",{max:Y.maxLength});return}this.sending=!0,this.sendButton.disabled=!0;try{let{comment:g}=await Ct(Mt("comments",this.entryId),{method:"POST",body:{body:o}});this.textarea.value="",this.onComment({action:"added",comment:g}),this.list&&(this.list.scrollTop=this.list.scrollHeight)}catch{this.error.textContent=q("failed")}finally{this.sending=!1,this.resize()}}}async resolve(o,g){try{let P=await Ct(Mt("resolve",this.entryId,o.id),{method:"POST",body:{resolved:g}});this.onComment({action:"updated",comment:P.comment})}catch{this.error.textContent=q("failed")}}async remove(o){this.confirming=null;try{await Ct(Mt("comment",this.entryId,o.id),{method:"DELETE"}),this.onComment({action:"deleted",comment:{id:o.id}})}catch{this.renderComments(),this.error.textContent=q("failed")}}async renderPreview(){let o=B("div",{class:"hibira-st-preview"},B("div",{class:"hibira-st-hint"},"\u2026"));this.card.replaceChildren(this.head(q("preview")),o);let g=null;try{({url:g}=await Ct(Mt("previewLink",this.entryId)))}catch{g=null}if(this.open!=="preview")return;if(!g){o.replaceChildren(B("div",{class:"hibira-st-hint"},q("preview_none")));return}let P=(0,Fe.default)(0,"M");P.addData(g),P.make();let E=B("div",{class:"hibira-st-qr",role:"img","aria-label":g});E.innerHTML=P.createSvgTag({cellSize:4,margin:0,scalable:!0});let L=B("button",{type:"button",class:"hibira-st-button",onclick:async()=>{try{await navigator.clipboard.writeText(g),L.lastChild.textContent=q("copied"),setTimeout(()=>L.lastChild.textContent=q("copy"),1500)}catch{window.getSelection().selectAllChildren(z)}}},Ot("copy",16),B("span",{},q("copy"))),z=B("div",{class:"hibira-st-link",title:g},g);o.replaceChildren(E,B("div",{class:"hibira-st-hint"},q("preview_scan")),z,B("div",{class:"hibira-st-row"},L,B("a",{class:"hibira-st-button",href:g,target:"_blank",rel:"noopener"},Ot("open",16),B("span",{},q("open")))))}destroy(){ft&&ft.unsubscribe(this.channelName),this.themeObserver.disconnect(),document.removeEventListener("keydown",this.onKey),this.root.remove()}};function Ue(){let A=location.pathname.match(Wn);return A&&!Kn.includes(A[1])?A[1]:null}async function Ft(){let A=Ue();if(pt&&pt.entryId===A||(pt&&(pt.destroy(),pt=null),!A))return;await Yn();let{features:o}=Y;!Y.enabled||!(o.presence||o.comments||o.livePreview)||Ue()!==A||pt||(pt=new se(A))}function qe(){if(!$e||window.HibiraStatamic)return;window.HibiraStatamic={get page(){return pt}};let A=document.createElement("style");A.textContent=Ne,document.head.append(A);for(let o of["pushState","replaceState"]){let g=history[o];history[o]=function(...P){let E=g.apply(this,P);return setTimeout(Ft,0),E}}window.addEventListener("popstate",()=>setTimeout(Ft,0)),setInterval(Ft,1500),Ft()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",qe):qe();})(); diff --git a/dist/preview.js b/dist/preview.js new file mode 100644 index 0000000..a2d0133 --- /dev/null +++ b/dist/preview.js @@ -0,0 +1 @@ +window.HibiraStatamicPreview=function(a){if(window.self!==window.top||window.HibiraStatamicPreview.started)return;window.HibiraStatamicPreview.started=!0;var i="hibira-statamic-scroll:"+location.pathname;try{var r=sessionStorage.getItem(i);if(r!==null){sessionStorage.removeItem(i);var o=function(){window.scrollTo(0,Number(r)||0)};document.readyState==="complete"?o():window.addEventListener("load",o)}}catch(e){}var n=1e3,s;function l(){try{sessionStorage.setItem(i,String(window.scrollY))}catch(e){}location.reload()}function c(){var e=new WebSocket(a.url);e.onmessage=function(d){var t;try{t=JSON.parse(d.data)}catch(u){return}t.event==="pusher:connection_established"?(n=1e3,e.send(JSON.stringify({event:"pusher:subscribe",data:{channel:a.channel}}))):t.event==="pusher:ping"?e.send(JSON.stringify({event:"pusher:pong",data:{}})):t.event==="refresh"&&t.channel===a.channel&&(clearTimeout(s),s=setTimeout(l,250))},e.onclose=function(){setTimeout(c,n),n=Math.min(n*2,3e4)}}c()}; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8f73fc5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,522 @@ +{ + "name": "statamic", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "devDependencies": { + "esbuild": "^0.25.0", + "pusher-js": "^8.4.0", + "qrcode-generator": "^1.4.4" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/pusher-js": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/pusher-js/-/pusher-js-8.6.0.tgz", + "integrity": "sha512-wShJPfCS/kYkCBVzVW67wa9cnQIgHTszEK2XHNrFkOgGruuGw081aERAxfRjfdFU+WcIt8x6dvbwkTW4iZuQ8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tweetnacl": "^1.0.3" + } + }, + "node_modules/qrcode-generator": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz", + "integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "dev": true, + "license": "Unlicense" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..29f04f2 --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "scripts": { + "build": "esbuild resources/js/cp.js --bundle --minify --format=iife --target=es2019 --loader:.css=text --outfile=dist/cp.js --legal-comments=none && esbuild resources/js/preview.js --minify --target=es2017 --outfile=dist/preview.js --legal-comments=none" + }, + "devDependencies": { + "esbuild": "^0.25.0", + "pusher-js": "^8.4.0", + "qrcode-generator": "^1.4.4" + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..62624a7 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + tests + + + diff --git a/resources/js/cp.css b/resources/js/cp.css new file mode 100644 index 0000000..8926606 --- /dev/null +++ b/resources/js/cp.css @@ -0,0 +1,258 @@ +.hibira-st { + --h-bg: #ffffff; + --h-fg: #1f2937; + --h-muted: #6b7280; + --h-border: #e5e7eb; + --h-soft: #f3f4f6; + --h-accent: #4f46e5; + --h-accent-fg: #ffffff; + --h-warn-bg: #fffbeb; + --h-warn-fg: #92400e; + --h-warn-border: #fcd34d; + --h-danger: #dc2626; + --h-shadow: 0 10px 30px rgba(15, 23, 42, .16), 0 2px 6px rgba(15, 23, 42, .08); + position: fixed; + right: 16px; + bottom: 16px; + z-index: 40; + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 8px; + max-width: calc(100vw - 32px); + font-family: inherit; + font-size: 14px; + line-height: 1.4; + color: var(--h-fg); +} +.hibira-st.hibira-st-dark { + --h-bg: #1f2125; + --h-fg: #e5e7eb; + --h-muted: #9ca3af; + --h-border: #374151; + --h-soft: #2b2e33; + --h-accent: #818cf8; + --h-accent-fg: #111827; + --h-warn-bg: #3a2e12; + --h-warn-fg: #fde68a; + --h-warn-border: #a16207; + --h-danger: #f87171; + --h-shadow: 0 10px 30px rgba(0, 0, 0, .5); +} +.hibira-st *, .hibira-st *::before, .hibira-st *::after { box-sizing: border-box; } +.hibira-st button { + font: inherit; + color: inherit; + background: none; + border: 0; + margin: 0; + padding: 0; + cursor: pointer; +} +.hibira-st button:focus-visible, .hibira-st textarea:focus-visible { + outline: 2px solid var(--h-accent); + outline-offset: 2px; +} +.hibira-st svg { display: block; } + +.hibira-st-dock { + display: flex; + align-items: center; + gap: 4px; + padding: 4px; + background: var(--h-bg); + border: 1px solid var(--h-border); + border-radius: 999px; + box-shadow: var(--h-shadow); +} +.hibira-st-people { display: flex; align-items: center; gap: 8px; padding: 0 6px 0 2px; } +.hibira-st-people[hidden] { display: none; } +.hibira-st-avatars { display: flex; } +.hibira-st-avatars > * + * { margin-left: -8px; } +.hibira-st-label { color: var(--h-muted); font-size: 13px; white-space: nowrap; max-width: 240px; overflow: hidden; text-overflow: ellipsis; } +.hibira-st-sep { width: 1px; height: 20px; background: var(--h-border); margin: 0 2px; } +.hibira-st-sep[hidden] { display: none; } + +.hibira-st-avatar { + position: relative; + flex: none; + width: 28px; + height: 28px; + border-radius: 999px; + border: 2px solid var(--h-bg); + color: #fff; + font-size: 11px; + font-weight: 600; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + background: var(--h-muted); +} +.hibira-st-avatar img { width: 100%; height: 100%; object-fit: cover; } +.hibira-st-avatar.hibira-st-more { background: var(--h-soft); color: var(--h-fg); } + +.hibira-st-icon { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 32px; + height: 32px; + padding: 0 8px; + border-radius: 999px; + color: var(--h-muted); +} +.hibira-st-icon:hover, .hibira-st-icon[aria-expanded="true"] { background: var(--h-soft); color: var(--h-fg); } +.hibira-st-icon.hibira-st-sm { min-width: 28px; height: 28px; padding: 0 6px; } +.hibira-st-count { font-size: 12px; font-weight: 600; } +.hibira-st-count:empty { display: none; } +.hibira-st-new .hibira-st-count { + background: var(--h-accent); + color: var(--h-accent-fg); + border-radius: 999px; + padding: 0 6px; +} + +[data-tip]:hover::after, [data-tip]:focus-visible::after { + content: attr(data-tip); + position: absolute; + bottom: calc(100% + 8px); + right: 0; + padding: 4px 8px; + border-radius: 6px; + background: #111827; + color: #f9fafb; + font-size: 12px; + font-weight: 400; + white-space: nowrap; + pointer-events: none; + z-index: 1; +} + +.hibira-st-status { width: 8px; height: 8px; border-radius: 999px; background: #d1d5db; margin: 0 8px 0 4px; } +.hibira-st-status[data-state="connected"] { background: #22c55e; } +.hibira-st-status[data-state="connecting"], .hibira-st-status[data-state="unavailable"] { background: #f59e0b; } + +.hibira-st-card { + width: 360px; + max-width: 100%; + background: var(--h-bg); + border: 1px solid var(--h-border); + border-radius: 12px; + box-shadow: var(--h-shadow); + overflow: hidden; +} +.hibira-st-card[hidden], .hibira-st-banner[hidden] { display: none; } +.hibira-st-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 8px 10px 14px; + border-bottom: 1px solid var(--h-border); + font-weight: 600; +} +.hibira-st-head-actions { display: flex; align-items: center; gap: 2px; } +.hibira-st-text-button { font-size: 12px; font-weight: 500; color: var(--h-muted); padding: 4px 8px; border-radius: 6px; } +.hibira-st-text-button:hover { background: var(--h-soft); color: var(--h-fg); } +.hibira-st-list { max-height: min(55vh, 460px); overflow-y: auto; padding: 4px 0; } +.hibira-st-empty { padding: 20px 16px; color: var(--h-muted); text-align: center; } +.hibira-st-comment { display: flex; gap: 10px; padding: 10px 14px; } +.hibira-st-comment + .hibira-st-comment { border-top: 1px solid var(--h-soft); } +.hibira-st-comment.hibira-st-resolved { opacity: .65; } +.hibira-st-comment-main { flex: 1; min-width: 0; } +.hibira-st-comment-meta { display: flex; align-items: baseline; gap: 6px; } +.hibira-st-comment-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.hibira-st-comment-time { color: var(--h-muted); font-size: 12px; white-space: nowrap; } +.hibira-st-comment-actions { margin-left: auto; display: flex; gap: 0; opacity: 0; transition: opacity .1s; } +.hibira-st-comment:hover .hibira-st-comment-actions, .hibira-st-comment:focus-within .hibira-st-comment-actions { opacity: 1; } +@media (hover: none) { .hibira-st-comment-actions { opacity: 1; } } +.hibira-st-comment-body { white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 2px; } +.hibira-st-comment-note { color: var(--h-muted); font-size: 12px; margin-top: 4px; } +.hibira-st-confirm { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 13px; } +.hibira-st-danger { color: var(--h-danger) !important; font-weight: 600; } +.hibira-st-comment .hibira-st-avatar { width: 28px; height: 28px; border: 0; } + +.hibira-st-compose { border-top: 1px solid var(--h-border); padding: 10px; display: flex; gap: 8px; align-items: flex-end; } +.hibira-st-compose textarea { + flex: 1; + min-height: 38px; + max-height: 160px; + resize: none; + padding: 8px 10px; + border: 1px solid var(--h-border); + border-radius: 8px; + background: var(--h-bg); + color: var(--h-fg); + font: inherit; + line-height: 1.4; +} +.hibira-st-compose textarea::placeholder { color: var(--h-muted); } +.hibira-st-send { + flex: none; + width: 38px; + height: 38px; + border-radius: 8px !important; + background: var(--h-accent) !important; + color: var(--h-accent-fg) !important; + display: flex; + align-items: center; + justify-content: center; +} +.hibira-st-send:disabled { opacity: .5; cursor: default; } +.hibira-st-error { color: var(--h-danger); font-size: 12px; padding: 0 12px 8px; } +.hibira-st-error:empty { display: none; } + +.hibira-st-preview { padding: 14px; display: flex; flex-direction: column; gap: 12px; } +.hibira-st-qr { align-self: center; width: 184px; height: 184px; padding: 8px; background: #fff; border-radius: 8px; } +.hibira-st-qr svg { width: 100%; height: 100%; } +.hibira-st-link { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + padding: 8px; + background: var(--h-soft); + border-radius: 6px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.hibira-st-hint { color: var(--h-muted); font-size: 13px; } +.hibira-st-row { display: flex; gap: 8px; } +.hibira-st-button { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px !important; + border: 1px solid var(--h-border) !important; + border-radius: 8px !important; + font-size: 13px !important; + font-weight: 500 !important; + text-decoration: none; + color: var(--h-fg); + background: var(--h-bg); +} +.hibira-st-button:hover { background: var(--h-soft) !important; } +.hibira-st-button.hibira-st-primary { background: var(--h-accent) !important; border-color: var(--h-accent) !important; color: var(--h-accent-fg) !important; } + +.hibira-st-banner { + width: 360px; + max-width: 100%; + display: flex; + gap: 10px; + align-items: flex-start; + padding: 12px 14px; + border: 1px solid var(--h-warn-border); + background: var(--h-warn-bg); + color: var(--h-warn-fg); + border-radius: 12px; + box-shadow: var(--h-shadow); +} +.hibira-st-banner-text { flex: 1; } +.hibira-st-banner .hibira-st-row { margin-top: 8px; } +.hibira-st-banner .hibira-st-button { border-color: var(--h-warn-border) !important; background: transparent; color: inherit; } + +@media (max-width: 640px) { + .hibira-st { right: 8px; bottom: 8px; max-width: calc(100vw - 16px); } + .hibira-st-label { display: none; } +} diff --git a/resources/js/cp.js b/resources/js/cp.js new file mode 100644 index 0000000..c8bf306 --- /dev/null +++ b/resources/js/cp.js @@ -0,0 +1,623 @@ +// Hibira for the Statamic control panel. +// +// On an entry's edit page this adds a small dock in the corner: who else +// has the entry open, a warning when one of them saves it, comments that +// arrive live, and a QR code of the live preview link for other devices. +// +// Plain DOM on purpose: the same file works in Statamic 5 (Vue 2) and +// Statamic 6 (Vue 3, Inertia). + +import Pusher from 'pusher-js'; +import qrcode from 'qrcode-generator'; +import css from './cp.css'; + +const SCRIPT = document.currentScript; +const BASE = SCRIPT ? SCRIPT.src.replace(/cp\.js(\?.*)?$/, '') : null; +const ENTRY_PATH = /\/collections\/[^/]+\/entries\/([A-Za-z0-9_-]{1,100})\/?$/; +const NOT_ENTRIES = ['create', 'actions', 'reorder']; + +let configPromise = null; +let config = null; +let pusher = null; +let page = null; + +// --------------------------------------------------------------------------- +// Helpers + +function t(key, replace = {}) { + let text = (config && config.strings && config.strings[key]) || key; + for (const [name, value] of Object.entries(replace)) { + text = text.split(':' + name).join(String(value)); + } + return text; +} + +function h(tag, attrs = {}, ...children) { + const el = document.createElement(tag); + for (const [name, value] of Object.entries(attrs)) { + if (value === null || value === undefined || value === false) continue; + if (name === 'class') el.className = value; + else if (name.startsWith('on')) el.addEventListener(name.slice(2), value); + else el.setAttribute(name, value === true ? '' : value); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + el.append(child instanceof Node ? child : document.createTextNode(String(child))); + } + return el; +} + +const ICONS = { + comment: '', + phone: '', + close: '', + check: '', + undo: '', + trash: '', + send: '', + copy: '', + open: '', + warn: '', +}; + +function icon(name, size = 18) { + const span = document.createElement('span'); + span.innerHTML = ``; + return span.firstChild; +} + +function iconButton(name, label, onclick, extra = '') { + return h('button', { type: 'button', class: 'hibira-st-icon ' + extra, 'aria-label': label, 'data-tip': label, onclick }, icon(name)); +} + +function avatar(member) { + const el = h('span', { class: 'hibira-st-avatar', style: `background:${member.color || '#6b7280'}` }); + if (member.avatar) { + const img = h('img', { src: member.avatar, alt: '' }); + img.addEventListener('error', () => img.replaceWith(document.createTextNode(member.initials || '?'))); + el.append(img); + } else { + el.append(member.initials || '?'); + } + return el; +} + +function relativeTime(iso) { + const seconds = Math.round((new Date(iso).getTime() - Date.now()) / 1000); + try { + const rtf = new Intl.RelativeTimeFormat(config.locale, { numeric: 'auto' }); + const steps = [[60, 'second'], [3600, 'minute', 60], [86400, 'hour', 3600], [604800, 'day', 86400]]; + if (Math.abs(seconds) < 45) return rtf.format(0, 'second'); + for (const [limit, unit, divisor = 1] of steps) { + if (Math.abs(seconds) < limit) return rtf.format(Math.round(seconds / divisor), unit); + } + return new Date(iso).toLocaleDateString(config.locale, { month: 'short', day: 'numeric', year: 'numeric' }); + } catch (e) { + return new Date(iso).toLocaleString(); + } +} + +function isDark() { + const root = document.documentElement; + if (root.classList.contains('dark')) return true; + if (root.classList.contains('light')) return false; + const meta = document.querySelector('meta[name="color-scheme"]'); + const scheme = meta ? meta.getAttribute('content') : 'auto'; + if (scheme === 'dark') return true; + if (scheme === 'light') return false; + return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; +} + +async function api(url, { method = 'GET', body } = {}) { + const headers = { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' }; + if (config && config.csrf) headers['X-CSRF-TOKEN'] = config.csrf; + if (pusher && pusher.connection.socket_id) headers['X-Socket-ID'] = pusher.connection.socket_id; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + + const response = await fetch(url, { + method, + headers, + credentials: 'same-origin', + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) throw new Error('HTTP ' + response.status); + return response.json(); +} + +function route(name, entry, comment) { + return config.routes[name] + .replace('__ENTRY__', encodeURIComponent(entry)) + .replace('__COMMENT__', encodeURIComponent(comment || '')); +} + +// --------------------------------------------------------------------------- +// Connection + +function loadConfig() { + if (!configPromise) { + configPromise = api(BASE + 'config') + .then((data) => (config = data)) + .catch(() => (config = { enabled: false })); + } + return configPromise; +} + +function connect() { + if (pusher) return pusher; + const c = config.connection; + pusher = new Pusher(c.key, { + cluster: 'hkg', + wsHost: c.host, + wsPort: c.port, + wssPort: c.port, + forceTLS: c.tls, + enabledTransports: ['ws', 'wss'], + disableStats: true, + channelAuthorization: { + customHandler: ({ socketId, channelName }, callback) => { + api(config.routes.auth, { method: 'POST', body: { socket_id: socketId, channel_name: channelName } }) + .then((data) => callback(null, data)) + .catch((error) => callback(error, null)); + }, + }, + }); + pusher.connection.bind('state_change', ({ current }) => page && page.setState(current)); + return pusher; +} + +// --------------------------------------------------------------------------- +// One entry's edit page + +class EntryPage { + constructor(entryId) { + this.entryId = entryId; + this.channelName = 'presence-hibira-statamic.entry.' + entryId; + this.comments = []; + this.loaded = false; + this.showResolved = false; + this.open = null; + this.unread = false; + this.subscribed = false; + this.confirming = null; + + this.build(); + this.subscribe(); + if (config.features.comments) this.loadComments(); + } + + // -- Layout --------------------------------------------------------------- + + build() { + const features = config.features; + + this.avatars = h('span', { class: 'hibira-st-avatars' }); + this.label = h('span', { class: 'hibira-st-label' }); + this.people = h('span', { class: 'hibira-st-people', hidden: true }, this.avatars, this.label); + this.separator = h('span', { class: 'hibira-st-sep', hidden: true }); + this.status = h('span', { class: 'hibira-st-status', 'data-state': 'connecting' }); + + this.commentsButton = features.comments + ? iconButton('comment', t('comments'), () => this.toggle('comments')) + : null; + if (this.commentsButton) { + this.count = h('span', { class: 'hibira-st-count' }); + this.commentsButton.append(this.count); + this.commentsButton.setAttribute('aria-expanded', 'false'); + } + + this.previewButton = features.livePreview + ? iconButton('phone', t('preview'), () => this.toggle('preview')) + : null; + if (this.previewButton) this.previewButton.setAttribute('aria-expanded', 'false'); + + this.dock = h('div', { class: 'hibira-st-dock' }, this.people, this.separator, this.commentsButton, this.previewButton, this.status); + this.banner = h('div', { class: 'hibira-st-banner', role: 'status', hidden: true }); + this.card = h('div', { class: 'hibira-st-card', hidden: true }); + this.root = h('div', { class: 'hibira-st' }, this.banner, this.card, this.dock); + + this.applyTheme(); + this.themeObserver = new MutationObserver(() => this.applyTheme()); + this.themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] }); + + this.onKey = (event) => { + if (event.key === 'Escape' && this.open) this.toggle(null); + }; + document.addEventListener('keydown', this.onKey); + document.body.append(this.root); + } + + applyTheme() { + this.root.classList.toggle('hibira-st-dark', isDark()); + } + + setState(state) { + this.status.dataset.state = state; + const label = state === 'connected' ? 'Hibira' : t('reconnecting'); + this.status.setAttribute('title', label); + } + + toggle(name) { + this.open = this.open === name ? null : name; + if (this.commentsButton) this.commentsButton.setAttribute('aria-expanded', String(this.open === 'comments')); + if (this.previewButton) this.previewButton.setAttribute('aria-expanded', String(this.open === 'preview')); + this.card.hidden = !this.open; + + if (this.open === 'comments') { + this.unread = false; + this.renderCount(); + this.renderComments(); + setTimeout(() => this.textarea.focus(), 0); + } else if (this.open === 'preview') { + this.renderPreview(); + } + } + + head(title, ...actions) { + return h('div', { class: 'hibira-st-head' }, + h('span', {}, title), + h('span', { class: 'hibira-st-head-actions' }, ...actions, iconButton('close', t('close'), () => this.toggle(null), 'hibira-st-sm'))); + } + + // -- Presence -------------------------------------------------------------- + + subscribe() { + this.setState(connect().connection.state); + this.channel = pusher.subscribe(this.channelName); + + this.channel.bind('pusher:subscription_succeeded', () => { + // Also after a reconnect: fetch what was missed. + if (this.subscribed && config.features.comments) this.loadComments(); + this.subscribed = true; + this.renderPeople(); + }); + this.channel.bind('pusher:member_added', () => this.renderPeople()); + this.channel.bind('pusher:member_removed', () => this.renderPeople()); + this.channel.bind('saved', (data) => this.onSaved(data)); + this.channel.bind('comment', (data) => this.onComment(data)); + } + + others() { + const others = []; + if (!this.channel || !this.channel.members) return others; + this.channel.members.each((member) => { + if (String(member.id) !== String(config.user.id)) others.push({ id: member.id, ...member.info }); + }); + return others; + } + + renderPeople() { + if (!config.features.presence) return; + const others = this.others(); + this.people.hidden = others.length === 0; + this.separator.hidden = others.length === 0 || (!this.commentsButton && !this.previewButton); + + this.avatars.replaceChildren(...others.slice(0, 3).map((member) => { + const el = avatar(member); + el.setAttribute('data-tip', member.name); + el.setAttribute('aria-label', member.name); + return el; + })); + if (others.length > 3) { + this.avatars.append(h('span', { class: 'hibira-st-avatar hibira-st-more' }, '+' + (others.length - 3))); + } + + this.label.textContent = others.length === 0 + ? '' + : others.length === 1 + ? t('here_one', { name: others[0].name }) + : t('here_many', { name: others[0].name, count: others.length - 1 }); + } + + onSaved(data) { + if (!config.features.presence) return; + if (data && data.by && String(data.by.id) === String(config.user.id)) return; + + const text = data && data.by ? t('saved_by', { name: data.by.name }) : t('saved_elsewhere'); + this.banner.replaceChildren( + h('span', { style: 'flex:none;margin-top:1px' }, icon('warn', 18)), + h('div', { class: 'hibira-st-banner-text' }, + text, + h('div', { class: 'hibira-st-row' }, + h('button', { type: 'button', class: 'hibira-st-button', onclick: () => location.reload() }, t('reload')), + h('button', { type: 'button', class: 'hibira-st-button', onclick: () => (this.banner.hidden = true) }, t('dismiss')))), + ); + this.banner.hidden = false; + } + + // -- Comments -------------------------------------------------------------- + + async loadComments() { + try { + const data = await api(route('comments', this.entryId)); + this.comments = data.comments || []; + this.loaded = true; + this.renderCount(); + if (this.open === 'comments') this.renderComments(); + } catch (e) { + // Shown as an empty list; the next reconnect tries again. + } + } + + onComment({ action, comment }) { + if (action === 'added') { + if (!this.comments.some((c) => c.id === comment.id)) this.comments.push(comment); + if (this.open !== 'comments' && String(comment.author.id) !== String(config.user.id)) this.unread = true; + } else if (action === 'updated') { + this.comments = this.comments.map((c) => (c.id === comment.id ? comment : c)); + } else if (action === 'deleted') { + this.comments = this.comments.filter((c) => c.id !== comment.id); + } + this.renderCount(); + if (this.open === 'comments') this.renderComments(); + } + + open_() { + return this.comments.filter((c) => !c.resolved_at); + } + + renderCount() { + if (!this.commentsButton) return; + const count = this.open_().length; + this.count.textContent = count ? String(count) : ''; + this.commentsButton.classList.toggle('hibira-st-new', this.unread); + const label = count ? t('comments_count', { count }) : t('comments'); + this.commentsButton.setAttribute('aria-label', label); + this.commentsButton.setAttribute('data-tip', this.unread ? label + ' •' : label); + } + + renderComments() { + if (!this.compose || !this.card.contains(this.compose)) this.buildCommentsCard(); + + const resolved = this.comments.filter((c) => c.resolved_at); + const visible = this.showResolved ? this.comments : this.open_(); + + this.resolvedToggle.hidden = resolved.length === 0; + this.resolvedToggle.textContent = this.showResolved ? t('hide_resolved') : t('show_resolved', { count: resolved.length }); + + const list = this.list; + const atEnd = list.scrollTop + list.clientHeight >= list.scrollHeight - 8; + const scrollTop = list.scrollTop; + + list.replaceChildren(...(visible.length + ? visible.map((comment) => this.renderComment(comment)) + : [h('div', { class: 'hibira-st-empty' }, this.loaded ? t('empty') : '…')])); + + list.scrollTop = atEnd ? list.scrollHeight : scrollTop; + } + + buildCommentsCard() { + this.resolvedToggle = h('button', { + type: 'button', + class: 'hibira-st-text-button', + onclick: () => { + this.showResolved = !this.showResolved; + this.renderComments(); + }, + }); + this.list = h('div', { class: 'hibira-st-list' }); + this.textarea = h('textarea', { + rows: 1, + placeholder: t('placeholder'), + 'aria-label': t('placeholder'), + maxlength: config.maxLength, + oninput: () => this.resize(), + onkeydown: (event) => { + if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { + event.preventDefault(); + this.send(); + } + }, + }); + this.sendButton = h('button', { + type: 'button', + class: 'hibira-st-send', + 'aria-label': t('send'), + 'data-tip': t('send_hint'), + onclick: () => this.send(), + }, icon('send', 18)); + this.error = h('div', { class: 'hibira-st-error', role: 'alert' }); + this.compose = h('div', { class: 'hibira-st-compose' }, this.textarea, this.sendButton); + + this.card.replaceChildren(this.head(t('comments'), this.resolvedToggle), this.list, this.compose, this.error); + this.resize(); + } + + renderComment(comment) { + const mine = String(comment.author.id) === String(config.user.id); + const canDelete = mine || config.user.super; + + const actions = h('span', { class: 'hibira-st-comment-actions' }, + comment.resolved_at + ? iconButton('undo', t('reopen'), () => this.resolve(comment, false), 'hibira-st-sm') + : iconButton('check', t('resolve'), () => this.resolve(comment, true), 'hibira-st-sm'), + canDelete ? iconButton('trash', t('delete'), () => { + this.confirming = comment.id; + this.renderComments(); + }, 'hibira-st-sm') : null); + + const confirm = this.confirming === comment.id + ? h('div', { class: 'hibira-st-confirm' }, + h('span', {}, t('delete_confirm')), + h('button', { type: 'button', class: 'hibira-st-text-button hibira-st-danger', onclick: () => this.remove(comment) }, t('delete')), + h('button', { + type: 'button', + class: 'hibira-st-text-button', + onclick: () => { + this.confirming = null; + this.renderComments(); + }, + }, t('dismiss'))) + : null; + + return h('div', { class: 'hibira-st-comment' + (comment.resolved_at ? ' hibira-st-resolved' : '') }, + avatar(comment.author), + h('div', { class: 'hibira-st-comment-main' }, + h('div', { class: 'hibira-st-comment-meta' }, + h('span', { class: 'hibira-st-comment-name' }, mine ? t('you') : comment.author.name), + h('time', { class: 'hibira-st-comment-time', datetime: comment.created_at, title: new Date(comment.created_at).toLocaleString(config.locale) }, relativeTime(comment.created_at)), + actions), + h('div', { class: 'hibira-st-comment-body' }, comment.body), + comment.resolved_by ? h('div', { class: 'hibira-st-comment-note' }, t('resolved_by', { name: comment.resolved_by.name })) : null, + confirm)); + } + + resize() { + if (!this.textarea) return; + this.textarea.style.height = 'auto'; + this.textarea.style.height = Math.min(this.textarea.scrollHeight + 2, 160) + 'px'; + this.sendButton.disabled = this.textarea.value.trim() === ''; + } + + async send() { + const body = this.textarea.value.trim(); + if (!body || this.sending) return; + if (body.length > config.maxLength) { + this.error.textContent = t('too_long', { max: config.maxLength }); + return; + } + + this.sending = true; + this.sendButton.disabled = true; + try { + const { comment } = await api(route('comments', this.entryId), { method: 'POST', body: { body } }); + this.textarea.value = ''; + this.onComment({ action: 'added', comment }); + if (this.list) this.list.scrollTop = this.list.scrollHeight; + } catch (e) { + this.error.textContent = t('failed'); + } finally { + this.sending = false; + this.resize(); + } + } + + async resolve(comment, resolved) { + try { + const data = await api(route('resolve', this.entryId, comment.id), { method: 'POST', body: { resolved } }); + this.onComment({ action: 'updated', comment: data.comment }); + } catch (e) { + this.error.textContent = t('failed'); + } + } + + async remove(comment) { + this.confirming = null; + try { + await api(route('comment', this.entryId, comment.id), { method: 'DELETE' }); + this.onComment({ action: 'deleted', comment: { id: comment.id } }); + } catch (e) { + this.renderComments(); + this.error.textContent = t('failed'); + } + } + + // -- Live preview on another device ---------------------------------------- + + async renderPreview() { + const body = h('div', { class: 'hibira-st-preview' }, h('div', { class: 'hibira-st-hint' }, '…')); + this.card.replaceChildren(this.head(t('preview')), body); + + let url = null; + try { + ({ url } = await api(route('previewLink', this.entryId))); + } catch (e) { + url = null; + } + if (this.open !== 'preview') return; + + if (!url) { + body.replaceChildren(h('div', { class: 'hibira-st-hint' }, t('preview_none'))); + return; + } + + const qr = qrcode(0, 'M'); + qr.addData(url); + qr.make(); + const code = h('div', { class: 'hibira-st-qr', role: 'img', 'aria-label': url }); + code.innerHTML = qr.createSvgTag({ cellSize: 4, margin: 0, scalable: true }); + + const copy = h('button', { + type: 'button', + class: 'hibira-st-button', + onclick: async () => { + try { + await navigator.clipboard.writeText(url); + copy.lastChild.textContent = t('copied'); + setTimeout(() => (copy.lastChild.textContent = t('copy')), 1500); + } catch (e) { + window.getSelection().selectAllChildren(link); + } + }, + }, icon('copy', 16), h('span', {}, t('copy'))); + + const link = h('div', { class: 'hibira-st-link', title: url }, url); + + body.replaceChildren( + code, + h('div', { class: 'hibira-st-hint' }, t('preview_scan')), + link, + h('div', { class: 'hibira-st-row' }, + copy, + h('a', { class: 'hibira-st-button', href: url, target: '_blank', rel: 'noopener' }, icon('open', 16), h('span', {}, t('open')))), + ); + } + + // ------------------------------------------------------------------------- + + destroy() { + if (pusher) pusher.unsubscribe(this.channelName); + this.themeObserver.disconnect(); + document.removeEventListener('keydown', this.onKey); + this.root.remove(); + } +} + +// --------------------------------------------------------------------------- +// Follow the control panel's navigation (Statamic 6 is a single page app) + +function entryIdFromLocation() { + const match = location.pathname.match(ENTRY_PATH); + return match && !NOT_ENTRIES.includes(match[1]) ? match[1] : null; +} + +async function sync() { + const entryId = entryIdFromLocation(); + if (page && page.entryId === entryId) return; + + if (page) { + page.destroy(); + page = null; + } + if (!entryId) return; + + await loadConfig(); + const { features } = config; + if (!config.enabled || !(features.presence || features.comments || features.livePreview)) return; + if (entryIdFromLocation() !== entryId || page) return; + + page = new EntryPage(entryId); +} + +function start() { + if (!BASE || window.HibiraStatamic) return; + window.HibiraStatamic = { get page() { return page; } }; + + const style = document.createElement('style'); + style.textContent = css; + document.head.append(style); + + for (const method of ['pushState', 'replaceState']) { + const original = history[method]; + history[method] = function (...args) { + const result = original.apply(this, args); + setTimeout(sync, 0); + return result; + }; + } + window.addEventListener('popstate', () => setTimeout(sync, 0)); + setInterval(sync, 1500); + sync(); +} + +if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); +else start(); diff --git a/resources/js/preview.js b/resources/js/preview.js new file mode 100644 index 0000000..59da858 --- /dev/null +++ b/resources/js/preview.js @@ -0,0 +1,53 @@ +// Runs on Statamic live preview pages opened outside the control panel +// (on a phone, in another browser). Listens on the preview token's public +// channel with the Pusher protocol and reloads the page, keeping the scroll +// position, whenever the entry changes in the control panel. +window.HibiraStatamicPreview = function (config) { + if (window.self !== window.top || window.HibiraStatamicPreview.started) return; + window.HibiraStatamicPreview.started = true; + + var key = 'hibira-statamic-scroll:' + location.pathname; + try { + var saved = sessionStorage.getItem(key); + if (saved !== null) { + sessionStorage.removeItem(key); + var restore = function () { window.scrollTo(0, Number(saved) || 0); }; + if (document.readyState === 'complete') restore(); + else window.addEventListener('load', restore); + } + } catch (e) {} + + var delay = 1000; + var timer; + + function reload() { + try { sessionStorage.setItem(key, String(window.scrollY)); } catch (e) {} + location.reload(); + } + + function connect() { + var socket = new WebSocket(config.url); + + socket.onmessage = function (message) { + var data; + try { data = JSON.parse(message.data); } catch (e) { return; } + + if (data.event === 'pusher:connection_established') { + delay = 1000; + socket.send(JSON.stringify({ event: 'pusher:subscribe', data: { channel: config.channel } })); + } else if (data.event === 'pusher:ping') { + socket.send(JSON.stringify({ event: 'pusher:pong', data: {} })); + } else if (data.event === 'refresh' && data.channel === config.channel) { + clearTimeout(timer); + timer = setTimeout(reload, 250); + } + }; + + socket.onclose = function () { + setTimeout(connect, delay); + delay = Math.min(delay * 2, 30000); + }; + } + + connect(); +}; diff --git a/resources/lang/en/messages.php b/resources/lang/en/messages.php new file mode 100644 index 0000000..a355ee3 --- /dev/null +++ b/resources/lang/en/messages.php @@ -0,0 +1,35 @@ + ':name also has this entry open', + 'here_many' => ':name and :count others also have this entry open', + 'saved_by' => ':name saved this entry. Reload to see their changes before you edit.', + 'saved_elsewhere' => 'This entry was saved somewhere else. Reload to see the latest version before you edit.', + 'reload' => 'Reload', + 'dismiss' => 'Dismiss', + 'comments' => 'Comments', + 'comments_count' => 'Comments (:count)', + 'empty' => 'No comments yet. Ask a question or leave a note for the next person.', + 'placeholder' => 'Write a comment…', + 'send' => 'Send', + 'send_hint' => 'Ctrl+Enter to send', + 'resolve' => 'Resolve', + 'reopen' => 'Reopen', + 'delete' => 'Delete', + 'delete_confirm' => 'Delete this comment?', + 'show_resolved' => 'Show resolved (:count)', + 'hide_resolved' => 'Hide resolved', + 'resolved_by' => 'Resolved by :name', + 'close' => 'Close', + 'failed' => 'Couldn’t save. Try again.', + 'too_long' => 'Comments can be up to :max characters.', + 'new_comment' => ':name commented', + 'you' => 'You', + 'preview' => 'Preview on another device', + 'preview_none' => 'Open Live Preview on this entry first. Its link then appears here.', + 'preview_scan' => 'Scan with your phone, or open the link in another browser. The page reloads each time you change the entry here.', + 'copy' => 'Copy link', + 'copied' => 'Copied', + 'open' => 'Open', + 'reconnecting' => 'Reconnecting…', +]; diff --git a/resources/lang/ja/messages.php b/resources/lang/ja/messages.php new file mode 100644 index 0000000..2c77915 --- /dev/null +++ b/resources/lang/ja/messages.php @@ -0,0 +1,35 @@ + ':name さんもこのエントリーを開いています', + 'here_many' => ':name さんほか :count 人もこのエントリーを開いています', + 'saved_by' => ':name さんがこのエントリーを保存しました。編集する前に再読み込みして変更を確認してください。', + 'saved_elsewhere' => 'このエントリーは別の場所で保存されました。編集する前に再読み込みして最新版を確認してください。', + 'reload' => '再読み込み', + 'dismiss' => '閉じる', + 'comments' => 'コメント', + 'comments_count' => 'コメント(:count)', + 'empty' => 'まだコメントはありません。質問や、次の人へのメモを残せます。', + 'placeholder' => 'コメントを書く…', + 'send' => '送信', + 'send_hint' => 'Ctrl+Enter で送信', + 'resolve' => '解決済みにする', + 'reopen' => '再オープン', + 'delete' => '削除', + 'delete_confirm' => 'このコメントを削除しますか?', + 'show_resolved' => '解決済みを表示(:count)', + 'hide_resolved' => '解決済みを隠す', + 'resolved_by' => ':name さんが解決済みにしました', + 'close' => '閉じる', + 'failed' => '保存できませんでした。もう一度お試しください。', + 'too_long' => 'コメントは :max 文字までです。', + 'new_comment' => ':name さんがコメントしました', + 'you' => 'あなた', + 'preview' => '別のデバイスでプレビュー', + 'preview_none' => 'まずこのエントリーでライブプレビューを開いてください。リンクがここに表示されます。', + 'preview_scan' => 'スマートフォンで読み取るか、別のブラウザーでリンクを開いてください。ここでエントリーを変更するたびにページが再読み込みされます。', + 'copy' => 'リンクをコピー', + 'copied' => 'コピーしました', + 'open' => '開く', + 'reconnecting' => '再接続中…', +]; diff --git a/resources/lang/ko/messages.php b/resources/lang/ko/messages.php new file mode 100644 index 0000000..480c109 --- /dev/null +++ b/resources/lang/ko/messages.php @@ -0,0 +1,35 @@ + ':name 님도 이 항목을 열어 두었습니다', + 'here_many' => ':name 님 외 :count 명도 이 항목을 열어 두었습니다', + 'saved_by' => ':name 님이 이 항목을 저장했습니다. 편집하기 전에 새로고침해서 변경 사항을 확인하세요.', + 'saved_elsewhere' => '이 항목이 다른 곳에서 저장되었습니다. 편집하기 전에 새로고침해서 최신 버전을 확인하세요.', + 'reload' => '새로고침', + 'dismiss' => '닫기', + 'comments' => '댓글', + 'comments_count' => '댓글 (:count)', + 'empty' => '아직 댓글이 없습니다. 질문하거나 다음 사람을 위한 메모를 남겨 보세요.', + 'placeholder' => '댓글 작성…', + 'send' => '보내기', + 'send_hint' => 'Ctrl+Enter로 보내기', + 'resolve' => '해결됨으로 표시', + 'reopen' => '다시 열기', + 'delete' => '삭제', + 'delete_confirm' => '이 댓글을 삭제할까요?', + 'show_resolved' => '해결된 댓글 보기 (:count)', + 'hide_resolved' => '해결된 댓글 숨기기', + 'resolved_by' => ':name 님이 해결함', + 'close' => '닫기', + 'failed' => '저장하지 못했습니다. 다시 시도하세요.', + 'too_long' => '댓글은 최대 :max자까지 쓸 수 있습니다.', + 'new_comment' => ':name 님이 댓글을 남겼습니다', + 'you' => '나', + 'preview' => '다른 기기에서 미리보기', + 'preview_none' => '먼저 이 항목에서 라이브 미리보기를 여세요. 그러면 링크가 여기에 나타납니다.', + 'preview_scan' => '휴대폰으로 스캔하거나 다른 브라우저에서 링크를 여세요. 여기서 항목을 바꿀 때마다 페이지가 새로고침됩니다.', + 'copy' => '링크 복사', + 'copied' => '복사됨', + 'open' => '열기', + 'reconnecting' => '다시 연결하는 중…', +]; diff --git a/resources/lang/th/messages.php b/resources/lang/th/messages.php new file mode 100644 index 0000000..9ea86ab --- /dev/null +++ b/resources/lang/th/messages.php @@ -0,0 +1,35 @@ + ':name เปิดรายการนี้อยู่ด้วย', + 'here_many' => ':name และอีก :count คนเปิดรายการนี้อยู่ด้วย', + 'saved_by' => ':name เพิ่งบันทึกรายการนี้ โปรดโหลดใหม่เพื่อดูการเปลี่ยนแปลงก่อนแก้ไขต่อ', + 'saved_elsewhere' => 'รายการนี้ถูกบันทึกจากที่อื่น โปรดโหลดใหม่เพื่อดูเวอร์ชันล่าสุดก่อนแก้ไขต่อ', + 'reload' => 'โหลดใหม่', + 'dismiss' => 'ปิด', + 'comments' => 'ความคิดเห็น', + 'comments_count' => 'ความคิดเห็น (:count)', + 'empty' => 'ยังไม่มีความคิดเห็น ถามคำถามหรือฝากโน้ตไว้ให้คนถัดไปได้', + 'placeholder' => 'เขียนความคิดเห็น…', + 'send' => 'ส่ง', + 'send_hint' => 'Ctrl+Enter เพื่อส่ง', + 'resolve' => 'ทำเครื่องหมายว่าแก้ไขแล้ว', + 'reopen' => 'เปิดอีกครั้ง', + 'delete' => 'ลบ', + 'delete_confirm' => 'ลบความคิดเห็นนี้ไหม', + 'show_resolved' => 'แสดงที่แก้ไขแล้ว (:count)', + 'hide_resolved' => 'ซ่อนที่แก้ไขแล้ว', + 'resolved_by' => ':name ทำเครื่องหมายว่าแก้ไขแล้ว', + 'close' => 'ปิด', + 'failed' => 'บันทึกไม่สำเร็จ โปรดลองอีกครั้ง', + 'too_long' => 'ความคิดเห็นยาวได้ไม่เกิน :max ตัวอักษร', + 'new_comment' => ':name แสดงความคิดเห็น', + 'you' => 'คุณ', + 'preview' => 'ดูตัวอย่างบนอุปกรณ์อื่น', + 'preview_none' => 'เปิดดูตัวอย่างสดของรายการนี้ก่อน แล้วลิงก์จะแสดงที่นี่', + 'preview_scan' => 'สแกนด้วยโทรศัพท์ หรือเปิดลิงก์ในเบราว์เซอร์อื่น หน้าจะโหลดใหม่ทุกครั้งที่คุณแก้ไขรายการที่นี่', + 'copy' => 'คัดลอกลิงก์', + 'copied' => 'คัดลอกแล้ว', + 'open' => 'เปิด', + 'reconnecting' => 'กำลังเชื่อมต่อใหม่…', +]; diff --git a/resources/lang/vi/messages.php b/resources/lang/vi/messages.php new file mode 100644 index 0000000..0bfec01 --- /dev/null +++ b/resources/lang/vi/messages.php @@ -0,0 +1,35 @@ + ':name cũng đang mở mục này', + 'here_many' => ':name và :count người khác cũng đang mở mục này', + 'saved_by' => ':name vừa lưu mục này. Hãy tải lại để xem thay đổi trước khi chỉnh sửa.', + 'saved_elsewhere' => 'Mục này vừa được lưu ở nơi khác. Hãy tải lại để xem bản mới nhất trước khi chỉnh sửa.', + 'reload' => 'Tải lại', + 'dismiss' => 'Đóng', + 'comments' => 'Bình luận', + 'comments_count' => 'Bình luận (:count)', + 'empty' => 'Chưa có bình luận. Hãy đặt câu hỏi hoặc để lại ghi chú cho người tiếp theo.', + 'placeholder' => 'Viết bình luận…', + 'send' => 'Gửi', + 'send_hint' => 'Ctrl+Enter để gửi', + 'resolve' => 'Đánh dấu đã xử lý', + 'reopen' => 'Mở lại', + 'delete' => 'Xóa', + 'delete_confirm' => 'Xóa bình luận này?', + 'show_resolved' => 'Hiện đã xử lý (:count)', + 'hide_resolved' => 'Ẩn đã xử lý', + 'resolved_by' => ':name đã đánh dấu xử lý', + 'close' => 'Đóng', + 'failed' => 'Không lưu được. Hãy thử lại.', + 'too_long' => 'Bình luận tối đa :max ký tự.', + 'new_comment' => ':name đã bình luận', + 'you' => 'Bạn', + 'preview' => 'Xem trước trên thiết bị khác', + 'preview_none' => 'Hãy mở Xem trước trực tiếp cho mục này trước. Liên kết sẽ xuất hiện ở đây.', + 'preview_scan' => 'Quét bằng điện thoại hoặc mở liên kết trong trình duyệt khác. Trang sẽ tải lại mỗi khi bạn sửa mục này ở đây.', + 'copy' => 'Sao chép liên kết', + 'copied' => 'Đã sao chép', + 'open' => 'Mở', + 'reconnecting' => 'Đang kết nối lại…', +]; diff --git a/resources/lang/zh_CN/messages.php b/resources/lang/zh_CN/messages.php new file mode 100644 index 0000000..13a09e9 --- /dev/null +++ b/resources/lang/zh_CN/messages.php @@ -0,0 +1,35 @@ + ':name 也打开了这篇内容', + 'here_many' => ':name 和另外 :count 人也打开了这篇内容', + 'saved_by' => ':name 刚保存了这篇内容。请先重新加载查看他们的更改,再继续编辑。', + 'saved_elsewhere' => '这篇内容在别处被保存了。请先重新加载最新版本,再继续编辑。', + 'reload' => '重新加载', + 'dismiss' => '关闭', + 'comments' => '评论', + 'comments_count' => '评论(:count)', + 'empty' => '还没有评论。可以提问,或给下一位留个备注。', + 'placeholder' => '写下评论…', + 'send' => '发送', + 'send_hint' => 'Ctrl+Enter 发送', + 'resolve' => '标记为已解决', + 'reopen' => '重新打开', + 'delete' => '删除', + 'delete_confirm' => '要删除这条评论吗?', + 'show_resolved' => '显示已解决(:count)', + 'hide_resolved' => '隐藏已解决', + 'resolved_by' => ':name 已标记为解决', + 'close' => '关闭', + 'failed' => '保存失败,请重试。', + 'too_long' => '评论最多 :max 个字。', + 'new_comment' => ':name 发表了评论', + 'you' => '你', + 'preview' => '在其他设备上预览', + 'preview_none' => '请先在这篇内容打开实时预览,链接就会出现在这里。', + 'preview_scan' => '用手机扫码,或在其他浏览器打开链接。每次在这里修改内容,页面都会自动重新加载。', + 'copy' => '复制链接', + 'copied' => '已复制', + 'open' => '打开', + 'reconnecting' => '正在重新连接…', +]; diff --git a/resources/lang/zh_TW/messages.php b/resources/lang/zh_TW/messages.php new file mode 100644 index 0000000..80cec25 --- /dev/null +++ b/resources/lang/zh_TW/messages.php @@ -0,0 +1,35 @@ + ':name 也開著這篇內容', + 'here_many' => ':name 和另外 :count 人也開著這篇內容', + 'saved_by' => ':name 剛儲存了這篇內容。請先重新載入看看他們的變更,再繼續編輯。', + 'saved_elsewhere' => '這篇內容在別處被儲存了。請先重新載入最新版本,再繼續編輯。', + 'reload' => '重新載入', + 'dismiss' => '關閉', + 'comments' => '留言', + 'comments_count' => '留言(:count)', + 'empty' => '還沒有留言。可以提問,或留個備註給下一位。', + 'placeholder' => '寫下留言…', + 'send' => '送出', + 'send_hint' => 'Ctrl+Enter 送出', + 'resolve' => '標記為已解決', + 'reopen' => '重新開啟', + 'delete' => '刪除', + 'delete_confirm' => '要刪除這則留言嗎?', + 'show_resolved' => '顯示已解決(:count)', + 'hide_resolved' => '隱藏已解決', + 'resolved_by' => ':name 已標記為解決', + 'close' => '關閉', + 'failed' => '儲存失敗,請再試一次。', + 'too_long' => '留言最多 :max 個字。', + 'new_comment' => ':name 留言了', + 'you' => '你', + 'preview' => '在其他裝置預覽', + 'preview_none' => '請先在這篇內容開啟即時預覽,連結就會出現在這裡。', + 'preview_scan' => '用手機掃描,或在其他瀏覽器開啟連結。每次在這裡修改內容,頁面都會自動重新載入。', + 'copy' => '複製連結', + 'copied' => '已複製', + 'open' => '開啟', + 'reconnecting' => '重新連線中…', +]; diff --git a/src/Channels.php b/src/Channels.php new file mode 100644 index 0000000..eee1874 --- /dev/null +++ b/src/Channels.php @@ -0,0 +1,50 @@ +> oldest first */ + public function all(string $entryId): array + { + $file = $this->file($entryId); + + if (! $this->files->exists($file)) { + return []; + } + + return $this->decode((string) $this->files->sharedGet($file)); + } + + public function count(string $entryId, bool $includeResolved = false): int + { + return count(array_filter( + $this->all($entryId), + fn (array $comment) => $includeResolved || $comment['resolved_at'] === null, + )); + } + + /** + * @param array $author + * @return array + */ + public function add(string $entryId, array $author, string $body): array + { + $comment = [ + 'id' => strtolower((string) Str::ulid()), + 'entry' => $entryId, + 'body' => $body, + 'author' => $author, + 'created_at' => now()->toIso8601String(), + 'resolved_at' => null, + 'resolved_by' => null, + ]; + + $this->change($entryId, function (array $comments) use ($comment) { + $comments[] = $comment; + + return $comments; + }); + + return $comment; + } + + /** @return array|null */ + public function find(string $entryId, string $commentId): ?array + { + foreach ($this->all($entryId) as $comment) { + if ($comment['id'] === $commentId) { + return $comment; + } + } + + return null; + } + + /** + * @param array|null $by who resolved it, or null to reopen + * @return array|null the changed comment + */ + public function resolve(string $entryId, string $commentId, ?array $by): ?array + { + $changed = null; + + $this->change($entryId, function (array $comments) use ($commentId, $by, &$changed) { + foreach ($comments as $i => $comment) { + if ($comment['id'] === $commentId) { + $comments[$i]['resolved_at'] = $by ? now()->toIso8601String() : null; + $comments[$i]['resolved_by'] = $by; + $changed = $comments[$i]; + } + } + + return $comments; + }); + + return $changed; + } + + public function delete(string $entryId, string $commentId): bool + { + $deleted = false; + + $this->change($entryId, function (array $comments) use ($commentId, &$deleted) { + $kept = array_values(array_filter($comments, fn (array $c) => $c['id'] !== $commentId)); + $deleted = count($kept) !== count($comments); + + return $kept; + }); + + return $deleted; + } + + /** Remove every comment of an entry. */ + public function forget(string $entryId): void + { + $this->files->delete($this->file($entryId)); + } + + /** @param callable(list>): list> $callback */ + protected function change(string $entryId, callable $callback): void + { + $file = $this->file($entryId); + $this->files->ensureDirectoryExists(dirname($file)); + + $handle = fopen($file, 'c+'); + if ($handle === false) { + throw new RuntimeException("Unable to open {$file}."); + } + + try { + flock($handle, LOCK_EX); + $comments = $callback($this->decode((string) stream_get_contents($handle))); + + ftruncate($handle, 0); + rewind($handle); + fwrite($handle, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n"); + fflush($handle); + } finally { + flock($handle, LOCK_UN); + fclose($handle); + } + + if ($comments === []) { + $this->files->delete($file); + } + } + + /** @return list> */ + protected function decode(string $json): array + { + $comments = json_decode($json, true); + + return is_array($comments) ? array_values(array_filter($comments, 'is_array')) : []; + } + + protected function file(string $entryId): string + { + if (! Channels::validId($entryId)) { + throw new InvalidArgumentException('Invalid entry ID.'); + } + + return rtrim($this->path, '/\\').DIRECTORY_SEPARATOR.$entryId.'.json'; + } +} diff --git a/src/Http/Controllers/AuthController.php b/src/Http/Controllers/AuthController.php new file mode 100644 index 0000000..ab9f672 --- /dev/null +++ b/src/Http/Controllers/AuthController.php @@ -0,0 +1,35 @@ +input('socket_id')); + $channel = (string) $request->input('channel_name'); + $entryId = Channels::entryId($channel); + + abort_unless($socketId !== null && $entryId !== null, 403); + abort_unless($realtime->configured(), 503); + + $this->viewableEntry($entryId); + $member = Members::info($user = $this->user()); + + return response( + $realtime->authorizePresence($channel, $socketId, $member['id'], array_diff_key($member, ['id' => true])), + 200, + ['Content-Type' => 'application/json'], + ); + } +} diff --git a/src/Http/Controllers/CommentController.php b/src/Http/Controllers/CommentController.php new file mode 100644 index 0000000..2ca0cb8 --- /dev/null +++ b/src/Http/Controllers/CommentController.php @@ -0,0 +1,88 @@ +viewableEntry($entry); + + return response()->json(['comments' => $this->comments->all($entry)]); + } + + public function store(Request $request, string $entry): JsonResponse + { + $this->viewableEntry($entry); + + $data = $request->validate([ + 'body' => ['required', 'string', 'max:'.(int) config('hibira-statamic.comments.max_length', 2000)], + ]); + + $body = trim(str_replace("\r\n", "\n", $data['body'])); + abort_if($body === '', 422); + + $comment = $this->comments->add($entry, Members::info($this->user()), $body); + $this->broadcast($request, $entry, 'added', $comment); + + return response()->json(['comment' => $comment], 201); + } + + public function resolve(Request $request, string $entry, string $comment): JsonResponse + { + $this->viewableEntry($entry); + + $resolved = $request->boolean('resolved', true); + $user = Members::info($this->user()); + + $changed = $this->comments->resolve( + $entry, + $comment, + $resolved ? ['id' => $user['id'], 'name' => $user['name']] : null, + ); + abort_if($changed === null, 404); + + $this->broadcast($request, $entry, 'updated', $changed); + + return response()->json(['comment' => $changed]); + } + + public function destroy(Request $request, string $entry, string $comment): JsonResponse + { + $this->viewableEntry($entry); + + $found = $this->comments->find($entry, $comment); + abort_if($found === null, 404); + + $user = $this->user(); + abort_unless($user->isSuper() || (string) ($found['author']['id'] ?? '') === (string) $user->id(), 403); + + $this->comments->delete($entry, $comment); + $this->broadcast($request, $entry, 'deleted', ['id' => $comment]); + + return response()->json(['deleted' => true]); + } + + /** @param array $comment */ + protected function broadcast(Request $request, string $entry, string $action, array $comment): void + { + $this->realtime->trigger( + (string) Channels::entry($entry), + 'comment', + ['action' => $action, 'comment' => $comment], + Realtime::socketId($request->header('X-Socket-ID')), + ); + } +} diff --git a/src/Http/Controllers/Concerns.php b/src/Http/Controllers/Concerns.php new file mode 100644 index 0000000..7f48b8a --- /dev/null +++ b/src/Http/Controllers/Concerns.php @@ -0,0 +1,32 @@ +user()->can('view', $entry), 403); + + return $entry; + } +} diff --git a/src/Http/Controllers/ConfigController.php b/src/Http/Controllers/ConfigController.php new file mode 100644 index 0000000..c64732b --- /dev/null +++ b/src/Http/Controllers/ConfigController.php @@ -0,0 +1,41 @@ +user(); + $config = config('hibira-statamic'); + + if (! $realtime->configured()) { + return response()->json(['enabled' => false]); + } + + return response()->json([ + 'enabled' => true, + 'connection' => $realtime->clientOptions(), + 'user' => Members::info($user) + ['super' => (bool) $user->isSuper()], + 'csrf' => csrf_token(), + 'features' => [ + 'presence' => (bool) $config['presence'], + 'comments' => (bool) $config['comments']['enabled'], + 'livePreview' => (bool) $config['live_preview'], + ], + 'maxLength' => (int) $config['comments']['max_length'], + 'routes' => Routes::urls(), + 'locale' => str_replace('_', '-', app()->getLocale()), + 'strings' => trans('hibira-statamic::messages'), + ]); + } +} diff --git a/src/Http/Controllers/PreviewLinkController.php b/src/Http/Controllers/PreviewLinkController.php new file mode 100644 index 0000000..1c390f6 --- /dev/null +++ b/src/Http/Controllers/PreviewLinkController.php @@ -0,0 +1,20 @@ +viewableEntry($entry); + + return response()->json(['url' => LivePreview::link((string) $this->user()->id(), $entry)]); + } +} diff --git a/src/Http/Controllers/ScriptController.php b/src/Http/Controllers/ScriptController.php new file mode 100644 index 0000000..6b49976 --- /dev/null +++ b/src/Http/Controllers/ScriptController.php @@ -0,0 +1,33 @@ +headers->get('If-None-Match') === $etag) { + return response('', 304, ['ETag' => $etag]); + } + + return response((string) file_get_contents(static::FILE), 200, [ + 'Content-Type' => 'application/javascript; charset=utf-8', + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'ETag' => $etag, + ]); + } + + public static function version(): string + { + return substr((string) md5_file(static::FILE), 0, 12); + } +} diff --git a/src/Http/Middleware/CaptureLivePreview.php b/src/Http/Middleware/CaptureLivePreview.php new file mode 100644 index 0000000..2d0e21c --- /dev/null +++ b/src/Http/Middleware/CaptureLivePreview.php @@ -0,0 +1,50 @@ +isSuccessful()) { + return $response; + } + + $name = (string) optional($request->route())->getName(); + if (! str_ends_with($name, 'collections.entries.preview.edit')) { + return $response; + } + + $data = $response->getData(true); + $token = $data['token'] ?? null; + $url = $data['url'] ?? null; + $entry = $request->route('entry'); + $entryId = is_object($entry) && method_exists($entry, 'id') ? (string) $entry->id() : (is_string($entry) ? $entry : null); + + if (! is_string($token) || ! is_string($url)) { + return $response; + } + + if ($entryId !== null && ($user = User::current())) { + LivePreview::remember((string) $user->id(), $entryId, $url); + } + + LivePreview::refresh($token); + + return $response; + } +} diff --git a/src/Http/Middleware/InjectPreviewReload.php b/src/Http/Middleware/InjectPreviewReload.php new file mode 100644 index 0000000..8f215a6 --- /dev/null +++ b/src/Http/Middleware/InjectPreviewReload.php @@ -0,0 +1,70 @@ +query('token'); + + if (! config('hibira-statamic.live_preview') + || ! is_string($token) || $token === '' + || ! $response->headers->has('X-Statamic-Live-Preview') + || $request->headers->get('Sec-Fetch-Dest') === 'iframe' + || ! str_contains((string) $response->headers->get('Content-Type'), 'text/html') + || ! $this->realtime->configured()) { + return $response; + } + + $html = $response->getContent(); + if (! is_string($html) || ($at = strripos($html, '')) === false) { + return $response; + } + + LivePreview::watch($token); + + $response->setContent(substr_replace($html, $this->script($token), $at, 0)); + + return $response; + } + + protected function script(string $token): string + { + $options = $this->realtime->clientOptions(); + $url = sprintf( + '%s://%s:%d/app/%s?protocol=7&client=hibira-statamic&version=0.1.0&flash=false', + $options['tls'] ? 'wss' : 'ws', + $options['host'], + $options['port'], + rawurlencode($options['key']), + ); + + $config = json_encode( + ['url' => $url, 'channel' => Channels::preview($token)], + JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT, + ); + + $source = (string) file_get_contents(__DIR__.'/../../../dist/preview.js'); + $nonce = method_exists(Vite::getFacadeRoot(), 'cspNonce') ? Vite::cspNonce() : null; + + return ''.trim($source).';HibiraStatamicPreview('.$config.');'; + } +} diff --git a/src/Http/Middleware/PointControlPanelEchoAtHibira.php b/src/Http/Middleware/PointControlPanelEchoAtHibira.php new file mode 100644 index 0000000..5c18ead --- /dev/null +++ b/src/Http/Middleware/PointControlPanelEchoAtHibira.php @@ -0,0 +1,66 @@ +realtime->configured() + && $this->statamicBroadcastingEnabled($request)) { + $options = $this->realtime->clientOptions(); + + Statamic::provideToScript(['broadcasting' => [ + 'enabled' => true, + 'endpoint' => config('broadcasting.auth_endpoint', url('/broadcasting/auth')), + 'connection' => 'hibira', + 'options' => [ + 'broadcaster' => 'pusher', + 'key' => $options['key'], + 'cluster' => 'hkg', + 'wsHost' => $options['host'], + 'wsPort' => $options['port'], + 'wssPort' => $options['port'], + 'forceTLS' => $options['tls'], + 'enabledTransports' => ['ws', 'wss'], + ], + ]]); + } + + return $next($request); + } + + /** + * Statamic turns its Echo client on only when the app has broadcasting + * set up (routes/channels.php). Left off otherwise, so the control panel + * doesn't open a connection nobody uses. + */ + protected function statamicBroadcastingEnabled(Request $request): bool + { + $broadcasting = Statamic::jsonVariables($request)['broadcasting'] ?? []; + + if (is_array($broadcasting) && ! empty($broadcasting['enabled'])) { + return true; + } + + // Statamic checks once, while booting, and may miss a provider that + // loads after it. Ask again now. + return array_key_exists(BroadcastServiceProvider::class, app()->getLoadedProviders()); + } +} diff --git a/src/Listeners/AnnounceEntrySaved.php b/src/Listeners/AnnounceEntrySaved.php new file mode 100644 index 0000000..a0ca70f --- /dev/null +++ b/src/Listeners/AnnounceEntrySaved.php @@ -0,0 +1,39 @@ +runningInConsole() && ! app()->runningUnitTests())) { + return; + } + + $channel = Channels::entry((string) $event->entry->id()); + if ($channel === null) { + return; + } + + $user = User::current(); + + $this->realtime->trigger($channel, 'saved', [ + 'by' => $user ? ['id' => (string) $user->id(), 'name' => (string) ($user->name() ?: $user->email())] : null, + 'at' => now()->toIso8601String(), + ]); + } +} diff --git a/src/LivePreview.php b/src/LivePreview.php new file mode 100644 index 0000000..05f1834 --- /dev/null +++ b/src/LivePreview.php @@ -0,0 +1,59 @@ +addMinutes(static::MINUTES)); + } + + public static function link(string $userId, string $entryId): ?string + { + $url = Cache::get(static::linkKey($userId, $entryId)); + + return is_string($url) ? $url : null; + } + + /** A preview page with this token is open outside the control panel. */ + public static function watch(string $token): void + { + Cache::put(static::watchKey($token), true, now()->addMinutes(static::MINUTES)); + } + + public static function watched(string $token): bool + { + return (bool) Cache::get(static::watchKey($token)); + } + + /** Reload preview pages of this token, if any were opened outside the control panel. */ + public static function refresh(string $token): void + { + if (static::watched($token)) { + app(Realtime::class)->trigger(Channels::preview($token), 'refresh', ['at' => now()->getTimestampMs()]); + } + } + + protected static function linkKey(string $userId, string $entryId): string + { + return 'hibira-statamic.preview-link.'.sha1($userId.'|'.$entryId); + } + + protected static function watchKey(string $token): string + { + return 'hibira-statamic.preview-watched.'.sha1($token); + } +} diff --git a/src/Members.php b/src/Members.php new file mode 100644 index 0000000..fd9e7d7 --- /dev/null +++ b/src/Members.php @@ -0,0 +1,48 @@ +id(); + $name = trim((string) ($user->name() ?: $user->email())); + + $avatar = null; + try { + $avatar = $user->avatar() ?: null; + } catch (\Throwable) { + // Some user repositories can't build an avatar URL. + } + + return [ + 'id' => $id, + 'name' => $name, + 'initials' => static::initials($user, $name), + 'avatar' => is_string($avatar) ? $avatar : null, + 'color' => static::COLORS[crc32($id) % count(static::COLORS)], + ]; + } + + protected static function initials(User $user, string $name): string + { + try { + $initials = (string) $user->initials(); + } catch (\Throwable) { + $initials = ''; + } + + if ($initials === '') { + $initials = mb_strtoupper(mb_substr($name, 0, 1)); + } + + return mb_substr($initials, 0, 2); + } +} diff --git a/src/Realtime.php b/src/Realtime.php new file mode 100644 index 0000000..746c703 --- /dev/null +++ b/src/Realtime.php @@ -0,0 +1,73 @@ +hibira->missingRealtimeCredentials() === []; + } + + /** @param array $data */ + public function trigger(string $channel, string $event, array $data, ?string $exceptSocket = null): void + { + if (! $this->configured()) { + return; + } + + try { + $this->hibira->realtime()->trigger( + $channel, + $event, + $data, + $exceptSocket ? ['socket_id' => $exceptSocket] : [], + ); + } catch (Throwable $e) { + report($e); + } + } + + /** @param array $info */ + public function authorizePresence(string $channel, string $socketId, string $userId, array $info): string + { + return $this->hibira->realtime()->authorizePresenceChannel($channel, $socketId, $userId, $info); + } + + /** + * What the browser needs to connect: the public key and WebSocket host. + * + * @return array{key: string, host: string, port: int, tls: bool} + */ + public function clientOptions(): array + { + $config = config('hibira'); + $tls = ($config['scheme'] ?? 'https') !== 'http'; + + return [ + 'key' => (string) ($config['key'] ?? ''), + 'host' => (string) ($config['host'] ?? 'ws.hibira.io'), + 'port' => (int) ($config['port'] ?? ($tls ? 443 : 80)), + 'tls' => $tls, + ]; + } + + /** A socket ID sent by the browser, or null when it is missing or malformed. */ + public static function socketId(?string $value): ?string + { + return is_string($value) && preg_match('/\A\d+\.\d+\z/', $value) ? $value : null; + } +} diff --git a/src/Routes.php b/src/Routes.php new file mode 100644 index 0000000..98074a2 --- /dev/null +++ b/src/Routes.php @@ -0,0 +1,48 @@ +name('hibira.')->group(function () { + Route::get('config', ConfigController::class)->name('config'); + Route::post('auth', AuthController::class)->name('auth'); + + Route::prefix('entries/{hibiraEntry}')->group(function () { + Route::get('comments', [CommentController::class, 'index'])->name('comments.index'); + Route::post('comments', [CommentController::class, 'store'])->name('comments.store'); + Route::post('comments/{hibiraComment}/resolve', [CommentController::class, 'resolve'])->name('comments.resolve'); + Route::delete('comments/{hibiraComment}', [CommentController::class, 'destroy'])->name('comments.destroy'); + Route::get('preview-link', PreviewLinkController::class)->name('preview-link'); + }); + }); + } + + /** @return array URLs for the browser, with placeholders for the entry and comment IDs */ + public static function urls(): array + { + $entry = ['hibiraEntry' => static::ENTRY]; + $comment = $entry + ['hibiraComment' => static::COMMENT]; + + return [ + 'auth' => cp_route('hibira.auth'), + 'comments' => cp_route('hibira.comments.index', $entry), + 'comment' => cp_route('hibira.comments.destroy', $comment), + 'resolve' => cp_route('hibira.comments.resolve', $comment), + 'previewLink' => cp_route('hibira.preview-link', $entry), + ]; + } +} diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php new file mode 100644 index 0000000..09b339d --- /dev/null +++ b/src/ServiceProvider.php @@ -0,0 +1,78 @@ + [AnnounceEntrySaved::class], + ]; + + protected $middlewareGroups = [ + 'web' => [InjectPreviewReload::class], + 'statamic.cp.authenticated' => [CaptureLivePreview::class, PointControlPanelEchoAtHibira::class], + ]; + + public function register(): void + { + parent::register(); + + $this->mergeConfigFrom(__DIR__.'/../config/hibira-statamic.php', 'hibira-statamic'); + + $this->app->singleton(Realtime::class); + $this->app->singleton(CommentStore::class, fn ($app) => new CommentStore( + new Filesystem, + (string) $app['config']->get('hibira-statamic.comments.path'), + )); + } + + public function bootAddon(): void + { + $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'hibira-statamic'); + + $this->publishes([ + __DIR__.'/../config/hibira-statamic.php' => config_path('hibira-statamic.php'), + ], 'hibira-statamic-config'); + + $this->publishes([ + __DIR__.'/../resources/lang' => $this->app->langPath('vendor/hibira-statamic'), + ], 'hibira-statamic-translations'); + + $this->registerCpRoutes(fn () => Routes::register()); + + $cp = trim((string) config('statamic.cp.route', 'cp'), '/'); + + if (! $this->app->routesAreCached()) { + Route::get($cp.'/hibira/cp.js', ScriptController::class)->name('statamic.cp.hibira.script'); + } + + Statamic::externalScript(url($cp.'/hibira/cp.js').'?v='.ScriptController::version()); + + $this->app['events']->listen(EntryDeleted::class, function (EntryDeleted $event) { + $id = (string) $event->entry->id(); + if (Channels::validId($id)) { + $this->app->make(CommentStore::class)->forget($id); + } + }); + } +} diff --git a/tests/CommentsTest.php b/tests/CommentsTest.php new file mode 100644 index 0000000..7f71b5a --- /dev/null +++ b/tests/CommentsTest.php @@ -0,0 +1,124 @@ +entry('post-1'); + $user = $this->superUser(); + + $response = $this->actingAs($user) + ->withHeader('X-Socket-ID', '11.22') + ->postJson('/cp/hibira/entries/post-1/comments', ['body' => " Can we shorten the intro?\r\nThanks "]); + + $response->assertCreated() + ->assertJsonPath('comment.body', "Can we shorten the intro?\nThanks") + ->assertJsonPath('comment.author.name', 'Ada Admin') + ->assertJsonPath('comment.resolved_at', null); + + $sent = $this->realtime->sent('comment'); + $this->assertCount(1, $sent); + $this->assertSame('presence-hibira-statamic.entry.post-1', $sent[0]['channel']); + $this->assertSame('added', $sent[0]['data']['action']); + $this->assertSame('11.22', $sent[0]['except']); + + $this->actingAs($user)->getJson('/cp/hibira/entries/post-1/comments') + ->assertOk() + ->assertJsonCount(1, 'comments') + ->assertJsonPath('comments.0.body', "Can we shorten the intro?\nThanks"); + + $this->assertFileExists($this->commentsPath.'/post-1.json'); + } + + public function test_empty_and_too_long_comments_are_refused(): void + { + $this->entry('post-1'); + $user = $this->superUser(); + config(['hibira-statamic.comments.max_length' => 10]); + + $this->actingAs($user)->postJson('/cp/hibira/entries/post-1/comments', ['body' => ''])->assertStatus(422); + $this->actingAs($user)->postJson('/cp/hibira/entries/post-1/comments', ['body' => str_repeat('a', 11)])->assertStatus(422); + $this->actingAs($user)->postJson('/cp/hibira/entries/missing/comments', ['body' => 'Hi'])->assertNotFound(); + } + + public function test_comments_can_be_resolved_and_reopened(): void + { + $this->entry('post-1'); + $user = $this->superUser(); + $id = $this->actingAs($user)->postJson('/cp/hibira/entries/post-1/comments', ['body' => 'Fix the typo'])->json('comment.id'); + + $this->actingAs($user)->postJson("/cp/hibira/entries/post-1/comments/{$id}/resolve", ['resolved' => true]) + ->assertOk() + ->assertJsonPath('comment.resolved_by.name', 'Ada Admin'); + $this->assertNotNull(app(CommentStore::class)->find('post-1', $id)['resolved_at']); + $this->assertSame(0, app(CommentStore::class)->count('post-1')); + + $this->actingAs($user)->postJson("/cp/hibira/entries/post-1/comments/{$id}/resolve", ['resolved' => false]) + ->assertOk() + ->assertJsonPath('comment.resolved_at', null); + + $this->assertSame(['added', 'updated', 'updated'], array_map( + fn ($sent) => $sent['data']['action'], + $this->realtime->sent('comment'), + )); + } + + public function test_only_the_author_or_a_super_user_can_delete_a_comment(): void + { + $this->entry('post-1'); + $ada = $this->superUser('ada', 'Ada'); + $bob = $this->superUser('bob', 'Bob'); + + $store = app(CommentStore::class); + $comment = $store->add('post-1', ['id' => 'someone-else', 'name' => 'Someone'], 'Hello'); + + // Super users may delete anyone's comment. + $this->actingAs($ada)->deleteJson("/cp/hibira/entries/post-1/comments/{$comment['id']}")->assertOk(); + $this->assertNull($store->find('post-1', $comment['id'])); + $this->assertSame('deleted', $this->realtime->sent('comment')[0]['data']['action']); + + $this->actingAs($bob)->deleteJson('/cp/hibira/entries/post-1/comments/nope')->assertNotFound(); + } + + public function test_non_super_users_can_delete_only_their_own_comments(): void + { + $this->setTestRoles(['editor' => ['access cp', 'view blog entries']]); + $this->entry('post-1'); + + $editor = $this->plainUser('ed', 'Ed'); + $editor->assignRole('editor')->save(); + + $store = app(CommentStore::class); + $theirs = $store->add('post-1', ['id' => 'someone-else', 'name' => 'Someone'], 'Hello'); + + $mine = $this->actingAs($editor)->postJson('/cp/hibira/entries/post-1/comments', ['body' => 'Mine']) + ->assertCreated() + ->json('comment.id'); + + $this->actingAs($editor)->deleteJson("/cp/hibira/entries/post-1/comments/{$theirs['id']}")->assertForbidden(); + $this->actingAs($editor)->deleteJson("/cp/hibira/entries/post-1/comments/{$mine}")->assertOk(); + } + + public function test_comments_go_when_the_entry_is_deleted(): void + { + $entry = $this->entry('post-1'); + app(CommentStore::class)->add('post-1', ['id' => 'a', 'name' => 'A'], 'Hello'); + + $entry->delete(); + + $this->assertSame([], app(CommentStore::class)->all('post-1')); + } + + public function test_the_store_rejects_ids_that_could_escape_the_folder(): void + { + $this->expectException(\InvalidArgumentException::class); + + app(CommentStore::class)->all('../secret'); + } +} diff --git a/tests/ControlPanelEchoTest.php b/tests/ControlPanelEchoTest.php new file mode 100644 index 0000000..157a3eb --- /dev/null +++ b/tests/ControlPanelEchoTest.php @@ -0,0 +1,35 @@ +set('broadcasting.default', 'hibira'); + } + + public function test_statamics_own_echo_is_pointed_at_hibira(): void + { + $html = $this->actingAs($this->superUser())->get('/cp/dashboard')->assertOk()->getContent(); + + preg_match('/var StatamicConfig = (\{.*?\});?\s*\n/s', $html, $match); + $this->assertNotEmpty($match, 'StatamicConfig not found on the dashboard'); + $broadcasting = json_decode($match[1], true)['broadcasting']; + + $this->assertTrue($broadcasting['enabled']); + $this->assertSame('pusher', $broadcasting['options']['broadcaster']); + $this->assertSame('ws.hibira.io', $broadcasting['options']['wsHost']); + $this->assertSame(443, $broadcasting['options']['wssPort']); + $this->assertSame('test-key', $broadcasting['options']['key']); + } +} diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php new file mode 100644 index 0000000..30d9884 --- /dev/null +++ b/tests/ControlPanelTest.php @@ -0,0 +1,150 @@ +get('/cp/hibira/cp.js'); + + $response->assertOk(); + $this->assertStringContainsString('javascript', $response->headers->get('Content-Type')); + $this->assertStringContainsString('hibira-st', $response->getContent()); + + $this->get('/cp/hibira/cp.js', ['If-None-Match' => '"'.ScriptController::version().'"'])->assertStatus(304); + } + + public function test_the_script_is_added_to_the_control_panel(): void + { + $scripts = Statamic::availableExternalScripts(request()); + + $this->assertNotEmpty(array_filter($scripts, fn ($url) => str_contains($url, '/cp/hibira/cp.js?v='))); + } + + public function test_config_needs_a_control_panel_user(): void + { + $this->getJson('/cp/hibira/config')->assertStatus(401); + } + + public function test_config_has_what_the_browser_needs(): void + { + $this->actingAs($this->superUser()) + ->getJson('/cp/hibira/config') + ->assertOk() + ->assertJsonPath('enabled', true) + ->assertJsonPath('connection.key', 'test-key') + ->assertJsonPath('connection.host', 'ws.hibira.io') + ->assertJsonPath('connection.tls', true) + ->assertJsonPath('user.id', 'super') + ->assertJsonPath('user.name', 'Ada Admin') + ->assertJsonPath('user.super', true) + ->assertJsonPath('features.comments', true) + ->assertJsonPath('strings.comments', 'Comments') + ->assertJsonPath('routes.comments', url('/cp/hibira/entries/__ENTRY__/comments')); + } + + public function test_config_is_off_without_credentials(): void + { + $this->realtime->isConfigured = false; + + $this->actingAs($this->superUser()) + ->getJson('/cp/hibira/config') + ->assertOk() + ->assertExactJson(['enabled' => false]); + } + + public function test_strings_follow_the_users_language(): void + { + $this->app->setLocale('zh_TW'); + + $this->actingAs($this->superUser()) + ->getJson('/cp/hibira/config') + ->assertJsonPath('strings.comments', '留言'); + } + + public function test_presence_subscriptions_are_signed_for_people_who_may_view_the_entry(): void + { + $this->entry('post-1'); + + $response = $this->actingAs($this->superUser())->postJson('/cp/hibira/auth', [ + 'socket_id' => '123.456', + 'channel_name' => 'presence-hibira-statamic.entry.post-1', + ]); + + $response->assertOk(); + $data = $response->json(); + $channelData = json_decode($data['channel_data'], true); + + $this->assertSame('super', $channelData['user_id']); + $this->assertSame('Ada Admin', $channelData['user_info']['name']); + $this->assertSame('AA', $channelData['user_info']['initials']); + + $expected = 'test-key:'.hash_hmac('sha256', '123.456:presence-hibira-statamic.entry.post-1:'.$data['channel_data'], 'test-secret'); + $this->assertSame($expected, $data['auth']); + } + + public function test_other_channels_and_missing_entries_are_refused(): void + { + $this->entry('post-1'); + $user = $this->superUser(); + + $this->actingAs($user)->postJson('/cp/hibira/auth', [ + 'socket_id' => '123.456', + 'channel_name' => 'presence-something-else', + ])->assertForbidden(); + + $this->actingAs($user)->postJson('/cp/hibira/auth', [ + 'socket_id' => 'nope', + 'channel_name' => 'presence-hibira-statamic.entry.post-1', + ])->assertForbidden(); + + $this->actingAs($user)->postJson('/cp/hibira/auth', [ + 'socket_id' => '123.456', + 'channel_name' => 'presence-hibira-statamic.entry.missing', + ])->assertNotFound(); + } + + public function test_people_who_cant_view_the_entry_cant_join(): void + { + $this->setTestRoles(['author' => ['access cp']]); + $this->entry('post-1'); + + $user = $this->plainUser(); + $user->assignRole('author')->save(); + + $this->actingAs($user)->postJson('/cp/hibira/auth', [ + 'socket_id' => '123.456', + 'channel_name' => 'presence-hibira-statamic.entry.post-1', + ])->assertForbidden(); + + $this->actingAs($user)->getJson('/cp/hibira/entries/post-1/comments')->assertForbidden(); + } + + public function test_saving_an_entry_tells_the_people_who_have_it_open(): void + { + $entry = $this->entry('post-1'); + $this->realtime->sent = []; + + $this->actingAs($this->superUser()); + $entry->set('title', 'Changed')->save(); + + $sent = $this->realtime->sent('saved'); + $this->assertCount(1, $sent); + $this->assertSame('presence-hibira-statamic.entry.post-1', $sent[0]['channel']); + $this->assertSame(['id' => 'super', 'name' => 'Ada Admin'], $sent[0]['data']['by']); + } + + public function test_saved_warnings_can_be_turned_off(): void + { + config(['hibira-statamic.presence' => false]); + $this->entry('post-1'); + + $this->assertSame([], $this->realtime->sent('saved')); + } +} diff --git a/tests/FakeRealtime.php b/tests/FakeRealtime.php new file mode 100644 index 0000000..9adcbfd --- /dev/null +++ b/tests/FakeRealtime.php @@ -0,0 +1,36 @@ +, except: ?string}> */ + public array $sent = []; + + public function __construct(Hibira $hibira, public bool $isConfigured = true) + { + parent::__construct($hibira); + } + + public function configured(): bool + { + return $this->isConfigured; + } + + public function trigger(string $channel, string $event, array $data, ?string $exceptSocket = null): void + { + if ($this->isConfigured) { + $this->sent[] = ['channel' => $channel, 'event' => $event, 'data' => $data, 'except' => $exceptSocket]; + } + } + + /** @return list, except: ?string}> */ + public function sent(string $event): array + { + return array_values(array_filter($this->sent, fn ($sent) => $sent['event'] === $event)); + } +} diff --git a/tests/FakesRoles.php b/tests/FakesRoles.php new file mode 100644 index 0000000..a03f352 --- /dev/null +++ b/tests/FakesRoles.php @@ -0,0 +1,36 @@ +> $roles */ + protected function setTestRoles(array $roles): void + { + $roles = collect($roles)->map(fn ($permissions, $handle) => Role::make()->handle($handle)->addPermission($permissions)); + + $fake = new class($roles) extends RoleRepository + { + public function __construct(protected Collection $fakeRoles) {} + + public function all(): Collection + { + return $this->fakeRoles; + } + + public function find(string $id): ?\Statamic\Contracts\Auth\Role + { + return $this->fakeRoles->get($id); + } + }; + + app()->instance(RepositoryContract::class, $fake); + Role::swap($fake); + } +} diff --git a/tests/LivePreviewTest.php b/tests/LivePreviewTest.php new file mode 100644 index 0000000..0b763a0 --- /dev/null +++ b/tests/LivePreviewTest.php @@ -0,0 +1,92 @@ +middleware('web')->get('/preview-page', fn () => response('

Draft

') + ->header('X-Statamic-Live-Preview', '1') + ->header('Content-Type', 'text/html; charset=UTF-8')); + + $router->middleware('web')->get('/normal-page', fn () => response('Live')); + } + + public function test_preview_pages_opened_outside_the_control_panel_get_the_reload_script(): void + { + $response = $this->get('/preview-page?live-preview=x&token=tok123', ['Sec-Fetch-Dest' => 'document']); + + $response->assertOk(); + $html = $response->getContent(); + $this->assertStringContainsString('HibiraStatamicPreview({', $html); + $this->assertStringContainsString(Channels::preview('tok123'), $html); + $this->assertStringContainsString('wss:\/\/ws.hibira.io:443\/app\/test-key', str_replace('/', '\/', $html)); + $this->assertLessThan(strpos($html, ''), strpos($html, '