@medipha/feed 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  export interface NewsfeedModuleProps {
2
2
  accessToken: string;
3
+ /** When the access token expires, in epoch seconds (the JWT `exp` claim). */
4
+ expireTime?: number;
3
5
  apiUrl: string;
4
6
  chatApiUrl: string;
5
7
  basePath: string;
package/dist/index.cjs CHANGED
@@ -34,5 +34,5 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
34
34
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes(`flac`)&&e.push(`
35
35
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
36
36
  Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.until!==void 0&&(typeof e.until!=`number`||Number.isNaN(e.until)))throw TypeError(`options.until, when provided, must be a number.`);if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw TypeError(`options.pauseSignal, when provided, must be an AbortSignal.`);if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
37
- `+this._getInvalidityExplanation().join(``));if(this._state===`executing`)throw Error(`Cannot call execute() while a previous call to execute() is still running.`);if(this._state===`canceled`)throw new Ek;if(this._state===`done`)return;if(this._composable&&this.output.state===`pending`)throw Error(`A composable conversion requires the output to be started. Call start() on the output before executing the conversion.`);this._state=`executing`,this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{this._state===`executing`&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener(`abort`,t);for(let e of this._trackPumps)e.done||(e.resolvers=Gg());if(this._executed)for(let e of this._trackPumps)e.wake?.();else{this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(e=>this._getTrackDuration(e)),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let e of this._trackPumps)e.start()}try{await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){throw this._state!==`canceled`&&this.cancel(),e}finally{e.pauseSignal?.removeEventListener(`abort`,t)}if(this._state===`canceled`)throw new Ek;let n=this._trackPumps.every(e=>e.done);this._state=n?`done`:`idle`,n&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!==`done`){if(this._state===`canceled`){z._warn(`Conversion already canceled.`);return}this._state=`canceled`;for(let e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,n){let r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:t});return}let i,{rotation:a,flip:o}=vg(await e.getRotation(),await e.getFlip(),t.rotate??0,t.flip??!1),s=a,c=o,l=t.rotate||t.flip?null:await e.getTransformationMatrix(),u=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),d=await e.getSquarePixelWidth(),f=await e.getSquarePixelHeight(),[p,m]=a%180==0?[d,f]:[f,d],h=t.crop;h&&=pb(h,p,m);let[g,_]=h?[h.width,h.height]:[p,m],v=g,y=_,b=v/y;t.width!==void 0&&t.height===void 0?(v=W_(t.width),y=W_(Math.round(v/b))):t.width===void 0&&t.height!==void 0?(y=W_(t.height),v=W_(Math.round(y*b))):t.width!==void 0&&t.height!==void 0&&(v=W_(t.width),y=W_(t.height));let x=this.output.format.getSupportedVideoCodecs(),S=t.alpha??`discard`,C=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!x.includes(r)||t.codec&&t.codec!==r||v!==g||y!==_||a!==0&&!u||o&&!u||!!h,w=null;if(!C){let t=new qw(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});if(n&&n.timestamp<this._startTimestamp&&n.timestamp+n.duration<=this._startTimestamp&&this._copyBoundaryPolicy===`shrink`&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0})),w=n,n){let e=this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp,this._startTimestamp):n.timestamp;if((this._copyBoundaryPolicy===`shrink`?e-this._startTimestamp:Math.max(this._startTimestamp-e,0))>this._copyBoundaryTolerance)C=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)e+this._timestampOffset!==0&&(C=!0);else{let t=L(this._startTimestamp-e,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);e+t===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+t,this._timestampOffsetAdjusted=!0):C=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&e<this._startTimestamp){let t=Math.min(this._startTimestamp-e,this._copyTimestampShiftTolerance);e+t>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+t):C=!0}}}if(C&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(C){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(x=x.filter(e=>e===t.codec));let r=Yb(t.quality,t.bitrate)??new Vb(`high`),p=await Zb(x,{width:t.process&&t.processedWidth?t.processedWidth:v,height:t.process&&t.processedHeight?t.processedHeight:y,quality:r});if(!p){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let m={codec:p,quality:r,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:S,hardwareAcceleration:t.hardwareAcceleration,transform:{}};j(m.transform);let b=v!==g||y!==_||a!==0&&(!u||t.process!==void 0)||o&&(!u||t.process!==void 0)||!!h||d!==await e.getCodedWidth()||f!==await e.getCodedHeight();if(!b){let n={stack:[],error:void 0,hasError:!1};try{let r=new _k({format:new sk,target:new ZO}),i=new sE(m);r.addVideoTrack(i),await r.start();let a=vk(n,await new nT(e,{hardwareAcceleration:t.hardwareAcceleration}).getSample(await e.getFirstTimestamp()),!1);if(a)try{await i.add(a),a.close(),await r.finalize()}catch(e){z._warn(`An error occurred when probing encoder support. Falling back to rerender path.`,e),r.cancel(),b=!0,m.transform.force=!0}else await r.cancel()}catch(e){n.error=e,n.hasError=!0}finally{yk(n)}}t.frameRate&&(m.transform.frameRate=t.frameRate),t.process&&(m.transform.process=t.process),b&&(s=0,c=!1,l=null,m.transform.width=v,m.transform.height=y,m.transform.fit=t.fit??`fill`,m.transform.rotate=t.rotate,m.transform.flip=t.flip,m.transform.crop=h,m.transform.alpha=S);let C=null;m.onEncodedSample=e=>{C=e.timestamp};let w=new sE(m);i=w,this._registerTrackPump(async r=>{let i=new nT(e,{hardwareAcceleration:t.hardwareAcceleration});for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let t={stack:[],error:void 0,hasError:!1};try{let i=vk(t,e,!1);if(this._state===`canceled`)break;let a=Math.max(this._startTimestamp,i.timestamp),o=Math.min(this._endTimestamp,i.timestamp+i.duration);if(a>=o)continue;i.setTimestamp(a+this._timestampOffset),i.setDuration(o-a),this._updateProgress(n,i.timestamp+i.duration),await w.add(i),i.close(),C!==null&&(this._synchronizer.shouldWait(n,C)&&await this._synchronizer.wait(C),await this._checkpoint(r,C))}catch(e){t.error=e,t.hasError=!0}finally{yk(t)}}w.close(),this._closeTrack(n)})}else{let t=new eE(r);i=t,this._registerTrackPump(async r=>{let i=new qw(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(w)for await(let e of i.packets(w,void 0,{verifyKeyPackets:!0})){if(this._state===`canceled`)break;if(e.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy===`shrink`)break;{let t=e,n=!1;for(let e=0;e<6;e++){let e=await i.getNextPacket(t,{metadataOnly:!0});if(!e)break;if(e.timestamp<this._endTimestamp){n=!0;break}t=e}if(!n)break}}let s=e.timestamp,c=e.timestamp+e.duration;this._copyBoundaryPolicy===`shrink`&&(s=Math.max(s,this._startTimestamp),c=Math.min(c,this._endTimestamp),c=Math.max(c,s)),s+=this._timestampOffset,c+=this._timestampOffset;let l=e.type;l===`key`&&o!==null&&s<o&&(l=`delta`),o=Math.max(o??-1/0,s);let u=e.clone({timestamp:s,duration:c-s,sideData:S===`discard`?{}:e.sideData,type:l});this._updateProgress(n,u.timestamp+u.duration),await t.add(u,a),this._synchronizer.shouldWait(n,u.timestamp)&&await this._synchronizer.wait(u.timestamp),await this._checkpoint(r,u.timestamp)}t.close(),this._closeTrack(n)})}let T=null;!t.group&&!this._composable&&(T=new hk);let ee=await e.getLanguageCode(),te=await e.getName(),E=await e.getDisposition(),ne=C?null:await e.getBitrate(),re=C?null:await e.getAverageBitrate(),ie=S===`keep`&&await e.canBeTransparent(),ae=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&ae===void 0){let n=t.frameRate??(await e.computePacketStats(wk)).averagePacketRate,r=C?this._startTimestamp:w?.timestamp??this._startTimestamp;ae=await this._estimateMaximumPacketCount(e,r,n)}this.output.addVideoTrack(i,{frameRate:t.frameRate,languageCode:d_(ee)?ee:void 0,name:te??void 0,disposition:E,rotation:s,flip:c,transformationMatrix:l??void 0,canBeTransparent:ie,group:T??t.group,bitrate:ne??void 0,averageBitrate:re??void 0,maximumPacketCount:ae}),this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(T)}async _processAudioTrack(e,t,n){let r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:t});return}let i,a=await e.getNumberOfChannels(),o=await e.getSampleRate(),s=t.numberOfChannels??a,c=t.sampleRate??o,l=null,u=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||s!==a||c!==o||!u.includes(r)||!!t.codec&&t.codec!==r||t.process!==void 0||t.sampleFormat!==void 0,f=null;if(!d){let t=new qw(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});n&&(this._copyBoundaryPolicy===`shrink`&&n.timestamp<this._startTimestamp||this._copyBoundaryPolicy===`expand`&&n.timestamp+n.duration<=this._startTimestamp)&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0}));let r=await e.getPreRollDuration();if(j(r!==null),n&&this._copyBoundaryPolicy===`expand`&&r>0&&(n=await t.getKeyPacket(n.timestamp-r,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0})),f=n,n){if((this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-n.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)n.timestamp+this._timestampOffset!==0&&(d=!0);else{let e=L(this._startTimestamp-n.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);n.timestamp+e===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+e,this._timestampOffsetAdjusted=!0):d=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&n.timestamp<this._startTimestamp){let e=Math.min(this._startTimestamp-n.timestamp,this._copyTimestampShiftTolerance);n.timestamp+e>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+e):d=!0}}}if(d&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(d){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(u=u.filter(e=>e===t.codec));let r=Yb(t.quality,t.bitrate)??new Vb(`high`),d=await Xb(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,quality:r});if(!d.some(e=>bE.includes(e))&&u.some(e=>bE.includes(e))&&(s!==Sk||c!==Ck)){let e=(await Xb(u,{numberOfChannels:Sk,sampleRate:Ck,quality:r})).find(e=>bE.includes(e));e&&(l=e,s=Sk,c=Ck)}else l=d[0]??null;if(l===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let f={codec:l,quality:r,transform:{sampleFormat:t.sampleFormat,process:t.process}};j(f.transform),s!==a&&(f.transform.numberOfChannels=s),c!==o&&(f.transform.sampleRate=c);let p=null;f.onEncodedSample=e=>{p=e.timestamp};let m=new gE(f);i=m,this._registerTrackPump(async t=>{let r=null,i=new aT(e);for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let i={stack:[],error:void 0,hasError:!1};try{let s=vk(i,e,!1);if(this._state===`canceled`)break;let c=0,l=s.numberOfFrames;if(s.timestamp<this._startTimestamp&&(c=Math.round((this._startTimestamp-s.timestamp)*s.sampleRate)),s.timestamp+s.duration>this._endTimestamp&&(l=Math.round((this._endTimestamp-s.timestamp)*s.sampleRate)),c>=l){s.close();continue}let u;if(c>0||l<s.numberOfFrames){let e=s.trim(c,l);if(s.close(),u=e,e.numberOfFrames===0){e.close();continue}}else u=s;let d=vk(i,u,!1);if(d.setTimestamp(d.timestamp+this._timestampOffset),r===null&&(r=this.output.format.supportsTimestampedMediaData?0:Math.round(d.timestamp*o)),r>0){let e={stack:[],error:void 0,hasError:!1};try{let i=Tb(s.format),c=new Uint8Array(i*r*a);(s.format===`u8`||s.format===`u8-planar`)&&c.fill(128);let l=vk(e,new wb({data:c,format:s.format,numberOfChannels:a,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(t,l,m,n,()=>p),r=0}catch(t){e.error=t,e.hasError=!0}finally{yk(e)}}await this._registerAudioSample(t,d,m,n,()=>p)}catch(e){i.error=e,i.hasError=!0}finally{yk(i)}}m.close(),this._closeTrack(n)})}else{let t=new lE(r);i=t,this._registerTrackPump(async r=>{let i=new qw(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(f)for await(let e of i.packets(f)){if(this._state===`canceled`||e.timestamp>=this._endTimestamp||this._copyBoundaryPolicy===`shrink`&&e.timestamp+e.duration>this._endTimestamp)break;let i=e.timestamp+this._timestampOffset;if(o!==null&&i<o)continue;o=i;let s=e.clone({timestamp:i,duration:e.duration});this._updateProgress(n,s.timestamp+s.duration),await t.add(s,a),this._synchronizer.shouldWait(n,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(r,s.timestamp)}t.close(),this._closeTrack(n)})}let p=null;!t.group&&!this._composable&&(p=new hk);let m=await e.getLanguageCode(),h=await e.getName(),g=await e.getDisposition(),_=d?null:await e.getBitrate(),v=d?null:await e.getAverageBitrate(),y=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&y===void 0){let t;d?(j(l),t=c/BE(l,c)):t=(await e.computePacketStats(wk)).averagePacketRate;let n=d?this._startTimestamp:f?.timestamp??this._startTimestamp;y=await this._estimateMaximumPacketCount(e,n,t)}this.output.addAudioTrack(i,{languageCode:d_(m)?m:void 0,name:h??void 0,disposition:g,group:p??t.group,bitrate:_??void 0,averageBitrate:v??void 0,maximumPacketCount:y}),this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(p)}async _estimateMaximumPacketCount(e,t,n){let r=Math.min(await this._getTrackDuration(e),this._endTimestamp),i=Math.max(r-t,0);return Math.ceil(1.5*n*i)+64}_getTrackDuration(e){let t=this._trackDurations.get(e);return t||(t=(async()=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration())(),this._trackDurations.set(e,t)),t}async _registerAudioSample(e,t,n,r,i){this._updateProgress(r,t.timestamp+t.duration),await n.add(t),t.close();let a=i();a!==null&&(this._synchronizer.shouldWait(r,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){let t={done:!1,resolvers:Gg(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!==`canceled`&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:n}=Gg();e.wake=n,await t}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;j(this._totalDuration!==null);let e=Math.min(...this._maxTimestamps.values()),t=L(e/this._totalDuration,0,1);this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,this.onProgress?.(t,e))}},Ek=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},Dk=1,Ok=class{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){let n=this.maxTimestamps.get(e);j(n!==void 0),this.maxTimestamps.set(e,Math.max(t,n));let r=this.computeMinAndMaybeResolve();return this.conversion._state===`canceled`||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-r>Dk}wait(e){let{promise:t,resolve:n}=Gg();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<Dk&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};async function kk(e,t){return/\.mp4$/i.test(t.name)?await(await e.getPrimaryVideoTrack())?.getCodec()===`avc`:!1}async function Ak(e,t){let n=new bT({source:new sw(e),formats:Hw});try{if(await kk(n,e))return e;let r=new XO,i=new _k({format:new sk,target:r}),a=await Tk.init({input:n,output:i,video:{codec:`avc`},audio:{codec:`aac`}});if(!a.isValid||(a.onProgress=t,await a.execute(),!r.buffer))return e;let o=e.name.replace(/\.[^.]+$/,``)+`.mp4`;return new File([r.buffer],o,{type:`video/mp4`})}catch{return e}finally{n.dispose()}}var jk=[{key:`image`,label:`Ảnh`,icon:(0,p.jsx)(h.PictureOutlined,{style:{color:`#45bd62`}}),accept:`.jpg,.jpeg,.png,.gif,.webp`,kind:`image`},{key:`video`,label:`Video`,icon:(0,p.jsx)(h.PlayCircleOutlined,{style:{color:`#f3425f`}}),accept:`.mp4,.webm,.mov`,kind:`video`},{key:`document`,label:`Tài liệu`,icon:(0,p.jsx)(h.FileTextOutlined,{style:{color:`var(--feed-primary)`}}),accept:`.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx`,kind:`document`}];function Mk({count:e,disabled:t,variant:n=`label`,onUploadStart:r,onUploaded:i}){let{api:a,me:o}=D(),s=o.mediaLimitsMb??re,c=e=>({file:t})=>{let n=t;r(),(e===`video`?Ak(n):Promise.resolve(n)).then(e=>a.uploadMedia(e,e.name)).then(i,e=>{u.message.error(og(e,n.name)),i(null)})},l=t=>(n,r)=>e+r.length>10?(u.message.warning(`Mỗi bài tối đa 10 tệp`),u.Upload.LIST_IGNORE):n.size>s[t]*1024*1024?(u.message.warning(`${n.name}: tối đa ${s[t]} MB`),u.Upload.LIST_IGNORE):!0,d=(e,r)=>n===`icon`?(0,p.jsx)(u.Tooltip,{title:e,children:(0,p.jsx)(u.Button,{type:`text`,shape:`circle`,size:`large`,icon:r,disabled:t,"aria-label":e,className:`med-feed-picker-icon`})}):(0,p.jsx)(u.Button,{type:`text`,icon:r,disabled:t,children:e});return(0,p.jsx)(p.Fragment,{children:jk.map(e=>(0,p.jsx)(u.Upload,{accept:e.accept,multiple:!0,showUploadList:!1,customRequest:c(e.kind),beforeUpload:l(e.kind),children:d(e.label,e.icon)},e.key))})}function Nk({media:e,uploadingCount:t,onRemove:n}){let r=e.filter(e=>e.kind!==`DOCUMENT`),i=e.filter(e=>e.kind===`DOCUMENT`);return e.length===0&&t===0?null:(0,p.jsxs)(`div`,{className:`med-feed-attached`,children:[(r.length>0||t>0)&&(0,p.jsxs)(`div`,{className:`med-feed-attached__images`,children:[r.map(e=>(0,p.jsxs)(`div`,{className:`med-feed-attached__thumb`,children:[e.kind===`VIDEO`?(0,p.jsxs)(p.Fragment,{children:[e.thumbnailUrl?(0,p.jsx)(`img`,{src:e.thumbnailUrl,alt:e.fileName,referrerPolicy:`no-referrer`}):(0,p.jsx)(`video`,{src:e.fileUrl,muted:!0,preload:`metadata`}),(0,p.jsx)(h.PlayCircleOutlined,{className:`med-feed-attached__play`})]}):(0,p.jsx)(`img`,{src:e.fileUrl,alt:e.fileName,referrerPolicy:`no-referrer`}),(0,p.jsx)(u.Button,{size:`small`,shape:`circle`,icon:(0,p.jsx)(h.CloseOutlined,{}),className:`med-feed-attached__remove`,"aria-label":`Bỏ ${e.fileName}`,onClick:()=>n(e.id)})]},e.id)),Array.from({length:t},(e,t)=>(0,p.jsx)(`div`,{className:`med-feed-attached__thumb med-feed-attached__thumb--loading`,children:(0,p.jsx)(h.LoadingOutlined,{})},`uploading-${t}`))]}),i.length>0&&(0,p.jsx)(u.List,{size:`small`,dataSource:i,renderItem:e=>(0,p.jsx)(u.List.Item,{actions:[(0,p.jsx)(u.Button,{type:`text`,size:`small`,icon:(0,p.jsx)(h.CloseOutlined,{}),"aria-label":`Bỏ ${e.fileName}`,onClick:()=>n(e.id)},`remove`)],children:(0,p.jsx)(u.List.Item.Meta,{avatar:(0,p.jsx)(jm,{fileName:e.fileName}),title:e.fileName,description:Zp(e.fileSize)})})})]})}var Pk=85,Fk=(0,f.forwardRef)(function({initialPost:e,onDirtyChange:t,onSaved:n,zoomed:r=!1,showPreview:i=!1},a){let{api:o,me:s}=D(),c=(0,f.useRef)(null),l=(0,f.useRef)(new Map(e?.mentionedUsers.map(e=>[e.fullName,e]))),d=(0,f.useRef)(crypto.randomUUID()),[m,g]=(0,f.useState)(Tp(e?.content??``,e?.mentionedUsers??[])),[_,v]=(0,f.useState)(e?.media??[]),[y,b]=(0,f.useState)(0),[x,S]=(0,f.useState)(null),[C,w]=(0,f.useState)(null),[T,ee]=(0,f.useState)(``),[te,E]=(0,f.useState)(!1),[ne,re]=(0,f.useState)(!0),[ie,ae]=(0,f.useState)({start:0,end:0}),[oe,se]=(0,f.useState)([]),[ce,le]=(0,f.useState)([]),ue=!!e,de=!m.trim()&&_.length===0,fe=Ee(m),pe=x!==null||y>0,me=_.length===0&&m.length<Pk&&!m.includes(`
37
+ `+this._getInvalidityExplanation().join(``));if(this._state===`executing`)throw Error(`Cannot call execute() while a previous call to execute() is still running.`);if(this._state===`canceled`)throw new Ek;if(this._state===`done`)return;if(this._composable&&this.output.state===`pending`)throw Error(`A composable conversion requires the output to be started. Call start() on the output before executing the conversion.`);this._state=`executing`,this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{this._state===`executing`&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener(`abort`,t);for(let e of this._trackPumps)e.done||(e.resolvers=Gg());if(this._executed)for(let e of this._trackPumps)e.wake?.();else{this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(e=>this._getTrackDuration(e)),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let e of this._trackPumps)e.start()}try{await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){throw this._state!==`canceled`&&this.cancel(),e}finally{e.pauseSignal?.removeEventListener(`abort`,t)}if(this._state===`canceled`)throw new Ek;let n=this._trackPumps.every(e=>e.done);this._state=n?`done`:`idle`,n&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!==`done`){if(this._state===`canceled`){z._warn(`Conversion already canceled.`);return}this._state=`canceled`;for(let e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,n){let r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:t});return}let i,{rotation:a,flip:o}=vg(await e.getRotation(),await e.getFlip(),t.rotate??0,t.flip??!1),s=a,c=o,l=t.rotate||t.flip?null:await e.getTransformationMatrix(),u=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),d=await e.getSquarePixelWidth(),f=await e.getSquarePixelHeight(),[p,m]=a%180==0?[d,f]:[f,d],h=t.crop;h&&=pb(h,p,m);let[g,_]=h?[h.width,h.height]:[p,m],v=g,y=_,b=v/y;t.width!==void 0&&t.height===void 0?(v=W_(t.width),y=W_(Math.round(v/b))):t.width===void 0&&t.height!==void 0?(y=W_(t.height),v=W_(Math.round(y*b))):t.width!==void 0&&t.height!==void 0&&(v=W_(t.width),y=W_(t.height));let x=this.output.format.getSupportedVideoCodecs(),S=t.alpha??`discard`,C=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!x.includes(r)||t.codec&&t.codec!==r||v!==g||y!==_||a!==0&&!u||o&&!u||!!h,w=null;if(!C){let t=new qw(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});if(n&&n.timestamp<this._startTimestamp&&n.timestamp+n.duration<=this._startTimestamp&&this._copyBoundaryPolicy===`shrink`&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0})),w=n,n){let e=this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp,this._startTimestamp):n.timestamp;if((this._copyBoundaryPolicy===`shrink`?e-this._startTimestamp:Math.max(this._startTimestamp-e,0))>this._copyBoundaryTolerance)C=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)e+this._timestampOffset!==0&&(C=!0);else{let t=L(this._startTimestamp-e,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);e+t===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+t,this._timestampOffsetAdjusted=!0):C=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&e<this._startTimestamp){let t=Math.min(this._startTimestamp-e,this._copyTimestampShiftTolerance);e+t>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+t):C=!0}}}if(C&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(C){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(x=x.filter(e=>e===t.codec));let r=Yb(t.quality,t.bitrate)??new Vb(`high`),p=await Zb(x,{width:t.process&&t.processedWidth?t.processedWidth:v,height:t.process&&t.processedHeight?t.processedHeight:y,quality:r});if(!p){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let m={codec:p,quality:r,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:S,hardwareAcceleration:t.hardwareAcceleration,transform:{}};j(m.transform);let b=v!==g||y!==_||a!==0&&(!u||t.process!==void 0)||o&&(!u||t.process!==void 0)||!!h||d!==await e.getCodedWidth()||f!==await e.getCodedHeight();if(!b){let n={stack:[],error:void 0,hasError:!1};try{let r=new _k({format:new sk,target:new ZO}),i=new sE(m);r.addVideoTrack(i),await r.start();let a=vk(n,await new nT(e,{hardwareAcceleration:t.hardwareAcceleration}).getSample(await e.getFirstTimestamp()),!1);if(a)try{await i.add(a),a.close(),await r.finalize()}catch(e){z._warn(`An error occurred when probing encoder support. Falling back to rerender path.`,e),r.cancel(),b=!0,m.transform.force=!0}else await r.cancel()}catch(e){n.error=e,n.hasError=!0}finally{yk(n)}}t.frameRate&&(m.transform.frameRate=t.frameRate),t.process&&(m.transform.process=t.process),b&&(s=0,c=!1,l=null,m.transform.width=v,m.transform.height=y,m.transform.fit=t.fit??`fill`,m.transform.rotate=t.rotate,m.transform.flip=t.flip,m.transform.crop=h,m.transform.alpha=S);let C=null;m.onEncodedSample=e=>{C=e.timestamp};let w=new sE(m);i=w,this._registerTrackPump(async r=>{let i=new nT(e,{hardwareAcceleration:t.hardwareAcceleration});for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let t={stack:[],error:void 0,hasError:!1};try{let i=vk(t,e,!1);if(this._state===`canceled`)break;let a=Math.max(this._startTimestamp,i.timestamp),o=Math.min(this._endTimestamp,i.timestamp+i.duration);if(a>=o)continue;i.setTimestamp(a+this._timestampOffset),i.setDuration(o-a),this._updateProgress(n,i.timestamp+i.duration),await w.add(i),i.close(),C!==null&&(this._synchronizer.shouldWait(n,C)&&await this._synchronizer.wait(C),await this._checkpoint(r,C))}catch(e){t.error=e,t.hasError=!0}finally{yk(t)}}w.close(),this._closeTrack(n)})}else{let t=new eE(r);i=t,this._registerTrackPump(async r=>{let i=new qw(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(w)for await(let e of i.packets(w,void 0,{verifyKeyPackets:!0})){if(this._state===`canceled`)break;if(e.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy===`shrink`)break;{let t=e,n=!1;for(let e=0;e<6;e++){let e=await i.getNextPacket(t,{metadataOnly:!0});if(!e)break;if(e.timestamp<this._endTimestamp){n=!0;break}t=e}if(!n)break}}let s=e.timestamp,c=e.timestamp+e.duration;this._copyBoundaryPolicy===`shrink`&&(s=Math.max(s,this._startTimestamp),c=Math.min(c,this._endTimestamp),c=Math.max(c,s)),s+=this._timestampOffset,c+=this._timestampOffset;let l=e.type;l===`key`&&o!==null&&s<o&&(l=`delta`),o=Math.max(o??-1/0,s);let u=e.clone({timestamp:s,duration:c-s,sideData:S===`discard`?{}:e.sideData,type:l});this._updateProgress(n,u.timestamp+u.duration),await t.add(u,a),this._synchronizer.shouldWait(n,u.timestamp)&&await this._synchronizer.wait(u.timestamp),await this._checkpoint(r,u.timestamp)}t.close(),this._closeTrack(n)})}let T=null;!t.group&&!this._composable&&(T=new hk);let ee=await e.getLanguageCode(),te=await e.getName(),E=await e.getDisposition(),ne=C?null:await e.getBitrate(),re=C?null:await e.getAverageBitrate(),ie=S===`keep`&&await e.canBeTransparent(),ae=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&ae===void 0){let n=t.frameRate??(await e.computePacketStats(wk)).averagePacketRate,r=C?this._startTimestamp:w?.timestamp??this._startTimestamp;ae=await this._estimateMaximumPacketCount(e,r,n)}this.output.addVideoTrack(i,{frameRate:t.frameRate,languageCode:d_(ee)?ee:void 0,name:te??void 0,disposition:E,rotation:s,flip:c,transformationMatrix:l??void 0,canBeTransparent:ie,group:T??t.group,bitrate:ne??void 0,averageBitrate:re??void 0,maximumPacketCount:ae}),this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(T)}async _processAudioTrack(e,t,n){let r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:t});return}let i,a=await e.getNumberOfChannels(),o=await e.getSampleRate(),s=t.numberOfChannels??a,c=t.sampleRate??o,l=null,u=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||s!==a||c!==o||!u.includes(r)||!!t.codec&&t.codec!==r||t.process!==void 0||t.sampleFormat!==void 0,f=null;if(!d){let t=new qw(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});n&&(this._copyBoundaryPolicy===`shrink`&&n.timestamp<this._startTimestamp||this._copyBoundaryPolicy===`expand`&&n.timestamp+n.duration<=this._startTimestamp)&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0}));let r=await e.getPreRollDuration();if(j(r!==null),n&&this._copyBoundaryPolicy===`expand`&&r>0&&(n=await t.getKeyPacket(n.timestamp-r,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0})),f=n,n){if((this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-n.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)n.timestamp+this._timestampOffset!==0&&(d=!0);else{let e=L(this._startTimestamp-n.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);n.timestamp+e===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+e,this._timestampOffsetAdjusted=!0):d=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&n.timestamp<this._startTimestamp){let e=Math.min(this._startTimestamp-n.timestamp,this._copyTimestampShiftTolerance);n.timestamp+e>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+e):d=!0}}}if(d&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(d){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(u=u.filter(e=>e===t.codec));let r=Yb(t.quality,t.bitrate)??new Vb(`high`),d=await Xb(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,quality:r});if(!d.some(e=>bE.includes(e))&&u.some(e=>bE.includes(e))&&(s!==Sk||c!==Ck)){let e=(await Xb(u,{numberOfChannels:Sk,sampleRate:Ck,quality:r})).find(e=>bE.includes(e));e&&(l=e,s=Sk,c=Ck)}else l=d[0]??null;if(l===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let f={codec:l,quality:r,transform:{sampleFormat:t.sampleFormat,process:t.process}};j(f.transform),s!==a&&(f.transform.numberOfChannels=s),c!==o&&(f.transform.sampleRate=c);let p=null;f.onEncodedSample=e=>{p=e.timestamp};let m=new gE(f);i=m,this._registerTrackPump(async t=>{let r=null,i=new aT(e);for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let i={stack:[],error:void 0,hasError:!1};try{let s=vk(i,e,!1);if(this._state===`canceled`)break;let c=0,l=s.numberOfFrames;if(s.timestamp<this._startTimestamp&&(c=Math.round((this._startTimestamp-s.timestamp)*s.sampleRate)),s.timestamp+s.duration>this._endTimestamp&&(l=Math.round((this._endTimestamp-s.timestamp)*s.sampleRate)),c>=l){s.close();continue}let u;if(c>0||l<s.numberOfFrames){let e=s.trim(c,l);if(s.close(),u=e,e.numberOfFrames===0){e.close();continue}}else u=s;let d=vk(i,u,!1);if(d.setTimestamp(d.timestamp+this._timestampOffset),r===null&&(r=this.output.format.supportsTimestampedMediaData?0:Math.round(d.timestamp*o)),r>0){let e={stack:[],error:void 0,hasError:!1};try{let i=Tb(s.format),c=new Uint8Array(i*r*a);(s.format===`u8`||s.format===`u8-planar`)&&c.fill(128);let l=vk(e,new wb({data:c,format:s.format,numberOfChannels:a,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(t,l,m,n,()=>p),r=0}catch(t){e.error=t,e.hasError=!0}finally{yk(e)}}await this._registerAudioSample(t,d,m,n,()=>p)}catch(e){i.error=e,i.hasError=!0}finally{yk(i)}}m.close(),this._closeTrack(n)})}else{let t=new lE(r);i=t,this._registerTrackPump(async r=>{let i=new qw(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(f)for await(let e of i.packets(f)){if(this._state===`canceled`||e.timestamp>=this._endTimestamp||this._copyBoundaryPolicy===`shrink`&&e.timestamp+e.duration>this._endTimestamp)break;let i=e.timestamp+this._timestampOffset;if(o!==null&&i<o)continue;o=i;let s=e.clone({timestamp:i,duration:e.duration});this._updateProgress(n,s.timestamp+s.duration),await t.add(s,a),this._synchronizer.shouldWait(n,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(r,s.timestamp)}t.close(),this._closeTrack(n)})}let p=null;!t.group&&!this._composable&&(p=new hk);let m=await e.getLanguageCode(),h=await e.getName(),g=await e.getDisposition(),_=d?null:await e.getBitrate(),v=d?null:await e.getAverageBitrate(),y=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&y===void 0){let t;d?(j(l),t=c/BE(l,c)):t=(await e.computePacketStats(wk)).averagePacketRate;let n=d?this._startTimestamp:f?.timestamp??this._startTimestamp;y=await this._estimateMaximumPacketCount(e,n,t)}this.output.addAudioTrack(i,{languageCode:d_(m)?m:void 0,name:h??void 0,disposition:g,group:p??t.group,bitrate:_??void 0,averageBitrate:v??void 0,maximumPacketCount:y}),this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(p)}async _estimateMaximumPacketCount(e,t,n){let r=Math.min(await this._getTrackDuration(e),this._endTimestamp),i=Math.max(r-t,0);return Math.ceil(1.5*n*i)+64}_getTrackDuration(e){let t=this._trackDurations.get(e);return t||(t=(async()=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration())(),this._trackDurations.set(e,t)),t}async _registerAudioSample(e,t,n,r,i){this._updateProgress(r,t.timestamp+t.duration),await n.add(t),t.close();let a=i();a!==null&&(this._synchronizer.shouldWait(r,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){let t={done:!1,resolvers:Gg(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!==`canceled`&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:n}=Gg();e.wake=n,await t}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;j(this._totalDuration!==null);let e=Math.min(...this._maxTimestamps.values()),t=L(e/this._totalDuration,0,1);this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,this.onProgress?.(t,e))}},Ek=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},Dk=1,Ok=class{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){let n=this.maxTimestamps.get(e);j(n!==void 0),this.maxTimestamps.set(e,Math.max(t,n));let r=this.computeMinAndMaybeResolve();return this.conversion._state===`canceled`||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-r>Dk}wait(e){let{promise:t,resolve:n}=Gg();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<Dk&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};async function kk(e,t){return/\.mp4$/i.test(t.name)?await(await e.getPrimaryVideoTrack())?.getCodec()===`avc`:!1}async function Ak(e,t){let n=new bT({source:new sw(e),formats:Hw});try{if(await kk(n,e))return e;let r=new XO,i=new _k({format:new sk({fastStart:`in-memory`}),target:r}),a=await Tk.init({input:n,output:i,video:{codec:`avc`},audio:{codec:`aac`}});if(!a.isValid){let t=a.discardedTracks.map(e=>e.reason).join(`, `);return console.warn(`Newsfeed: không convert được ${e.name} sang H.264 (${t})`),e}if(a.onProgress=t,await a.execute(),!r.buffer)return e;let o=e.name.replace(/\.[^.]+$/,``)+`.mp4`;return new File([r.buffer],o,{type:`video/mp4`})}catch(t){return console.warn(`Newsfeed: lỗi convert ${e.name} sang H.264`,t),e}finally{n.dispose()}}var jk=[{key:`image`,label:`Ảnh`,icon:(0,p.jsx)(h.PictureOutlined,{style:{color:`#45bd62`}}),accept:`.jpg,.jpeg,.png,.gif,.webp`,kind:`image`},{key:`video`,label:`Video`,icon:(0,p.jsx)(h.PlayCircleOutlined,{style:{color:`#f3425f`}}),accept:`.mp4,.webm,.mov`,kind:`video`},{key:`document`,label:`Tài liệu`,icon:(0,p.jsx)(h.FileTextOutlined,{style:{color:`var(--feed-primary)`}}),accept:`.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx`,kind:`document`}];function Mk({count:e,disabled:t,variant:n=`label`,onUploadStart:r,onUploaded:i}){let{api:a,me:o}=D(),s=o.mediaLimitsMb??re,c=e=>({file:t})=>{let n=t;r(),(e===`video`?Ak(n):Promise.resolve(n)).then(e=>a.uploadMedia(e,e.name)).then(i,e=>{u.message.error(og(e,n.name)),i(null)})},l=t=>(n,r)=>e+r.length>10?(u.message.warning(`Mỗi bài tối đa 10 tệp`),u.Upload.LIST_IGNORE):n.size>s[t]*1024*1024?(u.message.warning(`${n.name}: tối đa ${s[t]} MB`),u.Upload.LIST_IGNORE):!0,d=(e,r)=>n===`icon`?(0,p.jsx)(u.Tooltip,{title:e,children:(0,p.jsx)(u.Button,{type:`text`,shape:`circle`,size:`large`,icon:r,disabled:t,"aria-label":e,className:`med-feed-picker-icon`})}):(0,p.jsx)(u.Button,{type:`text`,icon:r,disabled:t,children:e});return(0,p.jsx)(p.Fragment,{children:jk.map(e=>(0,p.jsx)(u.Upload,{accept:e.accept,multiple:!0,showUploadList:!1,customRequest:c(e.kind),beforeUpload:l(e.kind),children:d(e.label,e.icon)},e.key))})}function Nk({media:e,uploadingCount:t,onRemove:n}){let r=e.filter(e=>e.kind!==`DOCUMENT`),i=e.filter(e=>e.kind===`DOCUMENT`);return e.length===0&&t===0?null:(0,p.jsxs)(`div`,{className:`med-feed-attached`,children:[(r.length>0||t>0)&&(0,p.jsxs)(`div`,{className:`med-feed-attached__images`,children:[r.map(e=>(0,p.jsxs)(`div`,{className:`med-feed-attached__thumb`,children:[e.kind===`VIDEO`?(0,p.jsxs)(p.Fragment,{children:[e.thumbnailUrl?(0,p.jsx)(`img`,{src:e.thumbnailUrl,alt:e.fileName,referrerPolicy:`no-referrer`}):(0,p.jsx)(`video`,{src:e.fileUrl,muted:!0,preload:`metadata`}),(0,p.jsx)(h.PlayCircleOutlined,{className:`med-feed-attached__play`})]}):(0,p.jsx)(`img`,{src:e.fileUrl,alt:e.fileName,referrerPolicy:`no-referrer`}),(0,p.jsx)(u.Button,{size:`small`,shape:`circle`,icon:(0,p.jsx)(h.CloseOutlined,{}),className:`med-feed-attached__remove`,"aria-label":`Bỏ ${e.fileName}`,onClick:()=>n(e.id)})]},e.id)),Array.from({length:t},(e,t)=>(0,p.jsx)(`div`,{className:`med-feed-attached__thumb med-feed-attached__thumb--loading`,children:(0,p.jsx)(h.LoadingOutlined,{})},`uploading-${t}`))]}),i.length>0&&(0,p.jsx)(u.List,{size:`small`,dataSource:i,renderItem:e=>(0,p.jsx)(u.List.Item,{actions:[(0,p.jsx)(u.Button,{type:`text`,size:`small`,icon:(0,p.jsx)(h.CloseOutlined,{}),"aria-label":`Bỏ ${e.fileName}`,onClick:()=>n(e.id)},`remove`)],children:(0,p.jsx)(u.List.Item.Meta,{avatar:(0,p.jsx)(jm,{fileName:e.fileName}),title:e.fileName,description:Zp(e.fileSize)})})})]})}var Pk=85,Fk=(0,f.forwardRef)(function({initialPost:e,onDirtyChange:t,onSaved:n,zoomed:r=!1,showPreview:i=!1},a){let{api:o,me:s}=D(),c=(0,f.useRef)(null),l=(0,f.useRef)(new Map(e?.mentionedUsers.map(e=>[e.fullName,e]))),d=(0,f.useRef)(crypto.randomUUID()),[m,g]=(0,f.useState)(Tp(e?.content??``,e?.mentionedUsers??[])),[_,v]=(0,f.useState)(e?.media??[]),[y,b]=(0,f.useState)(0),[x,S]=(0,f.useState)(null),[C,w]=(0,f.useState)(null),[T,ee]=(0,f.useState)(``),[te,E]=(0,f.useState)(!1),[ne,re]=(0,f.useState)(!0),[ie,ae]=(0,f.useState)({start:0,end:0}),[oe,se]=(0,f.useState)([]),[ce,le]=(0,f.useState)([]),ue=!!e,de=!m.trim()&&_.length===0,fe=Ee(m),pe=x!==null||y>0,me=_.length===0&&m.length<Pk&&!m.includes(`
38
38
  `),he=Uh(m,ie.start,ie.end),ge=Wh(m,ie.start),_e=e=>{e!==m&&(se(e=>[...e.slice(-99),m]),le([]),g(e))},ve=()=>{if(oe.length===0)return;let e=oe[oe.length-1];se(oe.slice(0,-1)),le([...ce,m]),g(e)},ye=()=>{if(ce.length===0)return;let e=ce[ce.length-1];le(ce.slice(0,-1)),se([...oe,m]),g(e)};(0,f.useEffect)(()=>{c.current?.focus()},[]),(0,f.useEffect)(()=>{t?.(!ue&&!de)},[ue,de,t]);let be=async t=>{if(de)return u.message.warning(`Bài viết cần có nội dung hoặc tệp đính kèm`),!1;S(t);let r={content:wp(m,l.current),mediaIds:_.map(e=>e.id)};try{let i;return e?(i=await o.updatePost(e.id,r),t===`submit`&&i.status===`DRAFT`&&(i=await o.submitPost(i.id))):(i=await o.createPost({...r,clientPostId:d.current,submit:t===`submit`}),d.current=crypto.randomUUID()),u.message.success(i.status===`DRAFT`?`Đã lưu nháp`:i.status===`PENDING`?`Bài viết đã vào hàng chờ duyệt`:i.status===`APPROVED`?`Bài viết đã được duyệt, chờ phát hành`:`Đã lưu bài viết`),n(i),!0}catch{return u.message.error(`Không lưu được bài viết, vui lòng thử lại`),!1}finally{S(null)}},xe=()=>c.current?.textarea??null,Se=()=>{let e=xe();e&&ae({start:e.selectionStart??0,end:e.selectionEnd??0})},Ce=e=>{_e(e.text),requestAnimationFrame(()=>{let t=xe();t?.focus(),t?.setSelectionRange(e.selectionStart,e.selectionEnd),Se()})},we=e=>{let t=xe(),n=t?.selectionStart??m.length,r=t?.selectionEnd??m.length;Ce(e(m,n,r))},Te=e=>we((t,n,r)=>Lh(t,n,r,e)),De=e=>we((t,n,r)=>Kh(t,n,r,e)),Oe={b:`bold`,i:`italic`,u:`underline`},ke=e=>{let t=xe(),n=t?.selectionStart??m.length,r=t?.selectionEnd??m.length;if(e.key===`Enter`&&(e.shiftKey||e.altKey)&&n===r){e.preventDefault(),Ce({text:`${m.slice(0,n)}\n${m.slice(r)}`,selectionStart:n+1,selectionEnd:n+1});return}if(e.key===`Enter`&&!e.shiftKey&&n===r){let t=Gh(m,n);if(t){e.preventDefault(),Ce(t);return}}let i=Oe[e.key.toLowerCase()];if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&i){e.preventDefault(),Te(i);return}if((e.ctrlKey||e.metaKey)&&!e.altKey){let t=e.key.toLowerCase();t===`z`&&!e.shiftKey?(e.preventDefault(),ve()):(t===`z`&&e.shiftKey||t===`y`)&&(e.preventDefault(),ye())}},Ae={id:e?.id??`draft-preview`,author:s.user??{id:s.userId,fullName:``,avatarUrl:null,departmentName:null},content:wp(m,l.current),mentionedUsers:[...l.current.values()],media:_,status:`PUBLISHED`,commentsLocked:e?.commentsLocked??!1,reactionCount:e?.reactionCount??0,topReactionTypes:e?.topReactionTypes??[],myReaction:null,commentCount:e?.commentCount??0,shareCount:e?.shareCount??0,sharedByMe:!1,createdAt:e?.createdAt??new Date().toISOString()};(0,f.useImperativeHandle)(a,()=>({saveDraft:()=>be(`draft`),isDirty:()=>!ue&&!de}));let je=(0,p.jsxs)(`div`,{className:`med-feed-composer-form`,children:[(0,p.jsxs)(`div`,{className:`med-feed-composer-form__author`,children:[(0,p.jsx)(lh,{size:40}),(0,p.jsx)(`span`,{className:`med-feed-composer-form__author-info`,children:(0,p.jsx)(`span`,{className:`med-feed-composer-form__author-name`,children:dm.name})})]}),(0,p.jsxs)(`div`,{className:`med-feed-composer-form__body`,children:[ne&&(0,p.jsx)(ag,{onInline:Te,onLines:De,activeInline:he,activeLines:ge,onColor:e=>we((t,n,r)=>Xh(t,n,r,e)),activeColor:$h(m,ie.start),onIndent:e=>we((t,n,r)=>Jh(t,n,r,e)),onSize:e=>we((t,n,r)=>Zh(t,n,r,e)),activeSize:eg(m,ie.start),onUndo:ve,onRedo:ye,canUndo:oe.length>0,canRedo:ce.length>0}),(0,p.jsx)(Cp,{ref:c,value:m,onChange:e=>{_e(e),Se()},onPick:e=>l.current.set(e.fullName,e),onKeyUp:Se,onMouseUp:Se,onKeyDown:ke,placeholder:`Tạo bài viết mới...`,autoSize:r||i?{minRows:12,maxRows:30}:{minRows:4,maxRows:14},style:C?{background:C,borderRadius:8,padding:`8px 12px`}:void 0,className:me?`med-feed-composer-form__text med-feed-composer-form__text--large`:`med-feed-composer-form__text`}),T&&(0,p.jsx)(u.Tag,{icon:(0,p.jsx)(h.EnvironmentOutlined,{}),color:`blue`,closable:!0,onClose:()=>ee(``),className:`med-feed-composer-form__location-tag`,children:T}),fe&&(0,p.jsx)(Om,{url:fe}),(0,p.jsx)(Nk,{media:_,uploadingCount:y,onRemove:e=>v(t=>t.filter(t=>t.id!==e))})]}),(0,p.jsxs)(`div`,{className:`med-feed-composer-form__toolbar`,children:[(0,p.jsxs)(`div`,{className:`med-feed-composer-form__toolbar-group`,children:[(0,p.jsx)(u.Popover,{trigger:`click`,content:(0,p.jsx)(`div`,{className:`med-feed-composer-form__color-grid`,children:[`#ffffff`,`#fde68a`,`#fca5a5`,`#86efac`,`#93c5fd`,`#d8b4fe`,`#f9a8d4`,`#c7d2fe`].map(e=>(0,p.jsx)(`button`,{type:`button`,className:`med-feed-composer-form__color-btn`,style:{background:e,borderColor:C===e?`var(--feed-primary)`:`#e5e7eb`},onClick:()=>w(e===`#ffffff`?null:e),"aria-label":e},e))}),children:(0,p.jsx)(u.Button,{type:`text`,icon:(0,p.jsx)(h.BgColorsOutlined,{style:{color:`var(--feed-primary)`,fontSize:20}}),className:`med-feed-composer-form__toolbar-btn`,"aria-label":`Màu nền`})}),(0,p.jsx)(u.Tooltip,{title:ne?`Ẩn định dạng`:`Định dạng văn bản`,children:(0,p.jsx)(u.Button,{type:`text`,icon:(0,p.jsx)(h.FontColorsOutlined,{style:{fontSize:18}}),className:ne?`med-feed-composer-form__toolbar-btn med-feed-composer-form__toolbar-btn--active`:`med-feed-composer-form__toolbar-btn`,"aria-label":`Định dạng văn bản`,"aria-pressed":ne,onClick:()=>re(e=>!e)})}),C&&C!==`#ffffff`&&(0,p.jsx)(u.Button,{type:`text`,size:`small`,onClick:()=>w(null),children:`Xóa màu`})]}),(0,p.jsx)(`div`,{className:`med-feed-composer-form__toolbar-group`,children:(0,p.jsx)(u.Popover,{trigger:`click`,overlayClassName:`med-feed-portal med-feed-emoji-popover`,content:(0,p.jsx)(up,{onPick:e=>_e(`${m}${e}`)}),children:(0,p.jsx)(u.Button,{type:`text`,icon:(0,p.jsx)(h.SmileOutlined,{style:{color:`#f7b928`,fontSize:20}}),className:`med-feed-composer-form__toolbar-btn`,"aria-label":`Cảm xúc`})})})]}),(0,p.jsxs)(`div`,{className:`med-feed-composer-form__add`,children:[(0,p.jsx)(`span`,{className:`med-feed-composer-form__add-label`,children:`Thêm vào bài viết của bạn`}),(0,p.jsxs)(`span`,{className:`med-feed-composer-form__add-actions`,children:[(0,p.jsx)(Mk,{variant:`icon`,count:_.length+y,disabled:x!==null,onUploadStart:()=>b(e=>e+1),onUploaded:e=>{b(e=>e-1),e&&v(t=>[...t,e])}}),(0,p.jsx)(u.Popover,{trigger:`click`,open:te,onOpenChange:E,content:(0,p.jsxs)(`div`,{style:{display:`flex`,gap:8,minWidth:220},children:[(0,p.jsx)(u.Input,{size:`small`,placeholder:`Nhập vị trí...`,value:T,onChange:e=>ee(e.target.value),onPressEnter:()=>E(!1),prefix:(0,p.jsx)(h.EnvironmentOutlined,{})}),(0,p.jsx)(u.Button,{size:`small`,type:`primary`,onClick:()=>E(!1),children:`Xong`})]}),children:(0,p.jsx)(u.Button,{type:`text`,shape:`circle`,size:`large`,icon:(0,p.jsx)(h.EnvironmentOutlined,{style:{color:`#10b981`,fontSize:22}}),"aria-label":`Vị trí`,className:`med-feed-picker-icon`})})]})]}),(0,p.jsx)(`div`,{className:`med-feed-composer-form__actions`,children:(0,p.jsx)(u.Button,{type:`primary`,block:!0,size:`large`,className:`med-feed-composer-form__submit`,disabled:pe||de,loading:x===`submit`,onClick:()=>void be(`submit`),children:`Hoàn thành`})})]});return i?(0,p.jsxs)(`div`,{className:`med-feed-composer-split`,children:[(0,p.jsx)(`div`,{className:`med-feed-composer-split__editor`,children:je}),(0,p.jsx)(`aside`,{className:`med-feed-composer-split__preview`,"aria-label":`Xem trước bài viết`,children:m.trim()||_.length>0?(0,p.jsx)(hh,{post:Ae,mode:`preview`}):(0,p.jsx)(`div`,{className:`med-feed-composer-split__empty`,children:`Nội dung bài sẽ hiện ở đây khi bạn gõ.`})})]}):je});function Ik({open:e,initialPost:t,onClose:n,onSaved:r}){let i=(0,f.useRef)(!1),a=(0,f.useRef)(null),[o,s]=(0,f.useState)(!1),[c,l]=(0,f.useState)(!1),[d,m]=(0,f.useState)(!1),[g,_]=(0,f.useState)(!1),v=(0,f.useCallback)(e=>{i.current=e},[]),y=()=>{if(!(a.current?.isDirty()??i.current)){n();return}s(!0)},b=async()=>{if(c)return;if(!a.current){s(!1),n();return}l(!0);let e=await a.current.saveDraft();l(!1),e&&(s(!1),n())};return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(u.Modal,{open:e,title:(0,p.jsxs)(`span`,{className:`med-feed-create-modal__title`,children:[t?`Sửa bài viết`:`Tạo bài viết`,(0,p.jsxs)(`span`,{className:`med-feed-create-modal__tools`,children:[(0,p.jsx)(u.Tooltip,{title:d?`Thoát toàn màn hình`:`Mở trình soạn toàn màn hình`,children:(0,p.jsx)(u.Button,{type:`text`,shape:`circle`,icon:d?(0,p.jsx)(h.CompressOutlined,{}):(0,p.jsx)(h.ExpandOutlined,{}),"aria-label":d?`Thu nhỏ`:`Phóng to`,"aria-pressed":d,className:d?`med-feed-create-modal__tool--active`:void 0,onClick:()=>m(e=>!e)})}),(0,p.jsx)(u.Tooltip,{title:g?`Ẩn`:`Xem`,children:(0,p.jsx)(u.Button,{type:`text`,shape:`circle`,icon:g?(0,p.jsx)(h.EyeInvisibleOutlined,{}):(0,p.jsx)(h.EyeOutlined,{}),"aria-label":`Xem trước`,"aria-pressed":g,className:g?`med-feed-create-modal__tool--active`:void 0,onClick:()=>_(e=>!e)})})]})]}),footer:null,width:d?`100vw`:g?1180:680,style:d?{top:0,maxWidth:`100vw`,margin:0,paddingBottom:0}:void 0,centered:!d,destroyOnClose:!0,maskClosable:!1,onCancel:y,closeIcon:(0,p.jsx)(h.CloseOutlined,{}),className:d?`med-feed-portal med-feed-create-modal med-feed-create-modal--fullscreen`:`med-feed-portal med-feed-create-modal`,children:(0,p.jsx)(Fk,{ref:a,zoomed:d,showPreview:g,initialPost:t,onDirtyChange:v,onSaved:e=>{i.current=!1,s(!1),r(e),n()}})}),(0,p.jsx)(u.Modal,{open:o,zIndex:1100,width:560,maskStyle:{zIndex:1099,background:`rgba(0, 0, 0, 0.65)`},title:`Lưu bài viết này làm bản nháp?`,onCancel:()=>{c||s(!1)},footer:[(0,p.jsx)(u.Button,{type:`text`,disabled:c,onClick:()=>{c||(s(!1),n())},children:`Xóa bản nhập`},`discard`),(0,p.jsx)(u.Button,{type:`primary`,loading:c,onClick:()=>void b(),children:`Lưu làm bản nháp`},`draft`)],centered:!0,destroyOnClose:!0,closeIcon:(0,p.jsx)(h.CloseOutlined,{}),className:`med-feed-portal med-feed-confirm-modal`,children:(0,p.jsx)(`p`,{children:`Nếu bỏ bây giờ, bạn sẽ mất bài viết này.`})})]})}function Lk({onSaved:e}){let{me:t}=D(),[n,r]=(0,f.useState)(null);return t.canPost?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(u.Button,{type:`primary`,className:`med-feed-create-button`,onClick:()=>r(Date.now()),children:[(0,p.jsx)(`span`,{className:`med-feed-create-button__icon`,"aria-hidden":!0}),`Tạo bài viết`]}),(0,p.jsx)(Ik,{open:n!==null,onClose:()=>r(null),onSaved:e},n??`closed`)]}):null}function Rk({title:e,description:t,extra:n}){return(0,p.jsxs)(`div`,{className:`med-feed-page-header`,children:[(0,p.jsxs)(`div`,{children:[(0,p.jsx)(u.Typography.Title,{level:4,className:`med-feed-page-header__title`,children:e}),t&&(0,p.jsx)(u.Typography.Text,{type:`secondary`,children:t})]}),n]})}var zk=[{key:`ALL`,label:`Tất cả`},{key:`DRAFT`,label:`Nháp`},{key:`PENDING`,label:`Chờ duyệt`},{key:`APPROVED`,label:`Đã duyệt`},{key:`PUBLISHED`,label:`Đang phát hành`},{key:`UNPUBLISHED`,label:`Đã gỡ`}];function Bk(){let{api:e,me:t,isPostFeed:n}=D(),[r,i]=(0,f.useState)(`ALL`),[a,o]=(0,f.useState)(null),s=r===`ALL`?void 0:r,c=Ie((0,f.useCallback)(t=>e.listMyPosts({status:s,cursor:t}),[e,s]),`my-posts|${r}`),l=async t=>{try{let n=await e.submitPost(t.id);c.updateItem(t.id,()=>n),u.message.success(n.status===`APPROVED`?`Bài viết đã được duyệt, chờ phát hành`:`Bài viết đã vào hàng chờ duyệt`)}catch{u.message.error(`Không gửi được bài viết`)}};return(0,p.jsxs)(`div`,{className:`med-feed-my-posts med-feed-stack`,children:[(0,p.jsx)(Rk,{title:`Bài của tôi`,description:`Quản lý nháp, bài chờ duyệt và bài đang phát hành của bạn`,extra:n&&(0,p.jsx)(Lk,{onSaved:e=>{(r===`ALL`||r===e.status)&&c.prependItem(e)}})}),(0,p.jsx)(u.Tabs,{activeKey:r,onChange:e=>i(e),items:zk.map(e=>({key:e.key,label:e.label}))}),(0,p.jsx)(gh,{list:c,emptyText:`Không có bài viết`,statusOnTop:!0,hideModeration:!0,renderHeaderActions:e=>(e.status===`DRAFT`||e.status===`PENDING`)&&(0,p.jsx)(u.Button,{className:`med-feed-my-posts__edit`,size:`small`,icon:(0,p.jsx)(h.EditOutlined,{}),onClick:()=>o(e),children:`Sửa`}),renderFooter:e=>n&&e.status===`DRAFT`&&t.canPost&&(0,p.jsx)(u.Space,{wrap:!0,className:`med-feed-my-posts__footer-actions`,children:(0,p.jsx)(u.Button,{className:`med-feed-my-posts__done`,type:`primary`,icon:(0,p.jsx)(h.SendOutlined,{}),onClick:()=>void l(e),children:`Hoàn thành`})})}),(0,p.jsx)(Ik,{open:a!==null,initialPost:a??void 0,onClose:()=>o(null),onSaved:e=>c.updateItem(e.id,()=>e)},a?.id??`closed`)]})}function Vk({value:e,onChange:t,aspectRatio:n=`16 / 9`,maxWidth:r}){let{api:i}=D(),a=(0,f.useRef)(null),[o,s]=(0,f.useState)(!1),[c,l]=(0,f.useState)(!1),d=async e=>{if(e){if(!e.type.startsWith(`image/`)){u.message.error(`Chỉ nhận file ảnh`);return}s(!0);try{let n=await i.uploadMedia(e,e.name);t?.(n.fileUrl)}catch{u.message.error(`Không tải được ảnh`)}finally{s(!1)}}};return(0,p.jsxs)(`div`,{className:c?`med-feed-image-field med-feed-image-field--drag`:`med-feed-image-field`,style:{maxWidth:r},onDragOver:e=>{e.preventDefault(),l(!0)},onDragLeave:()=>l(!1),onDrop:e=>{e.preventDefault(),l(!1),d(e.dataTransfer.files?.[0])},children:[(0,p.jsxs)(`button`,{type:`button`,className:`med-feed-image-field__drop`,style:{aspectRatio:n},disabled:o,onClick:()=>a.current?.click(),children:[e?(0,p.jsx)(`img`,{src:e,alt:`Ảnh đã chọn`,className:`med-feed-image-field__preview`}):(0,p.jsxs)(`span`,{className:`med-feed-image-field__placeholder`,children:[(0,p.jsx)(h.PictureOutlined,{}),(0,p.jsx)(`strong`,{children:`Tải ảnh lên`}),(0,p.jsx)(`span`,{children:`Kéo thả hoặc bấm để chọn ảnh`})]}),e&&(0,p.jsxs)(`span`,{className:`med-feed-image-field__change`,children:[(0,p.jsx)(h.CameraOutlined,{}),` Đổi ảnh`]}),o&&(0,p.jsxs)(`span`,{className:`med-feed-image-field__busy`,children:[(0,p.jsx)(h.LoadingOutlined,{}),` Đang tải...`]})]}),(0,p.jsx)(`input`,{ref:a,type:`file`,accept:`image/*`,hidden:!0,onChange:e=>{d(e.target.files?.[0]),e.target.value=``}})]})}var Hk=`DD/MM/YYYY HH:mm`;function Uk(){let{api:e}=D(),t=hp((0,f.useCallback)(()=>e.listManageEvents(),[e]),`manage-events`),[n,r]=(0,f.useState)(null),[i,a]=(0,f.useState)(!1),[o]=u.Form.useForm(),s=e=>{o.setFieldsValue(e===`new`?{title:``,startsAt:(0,v.default)().add(1,`day`).startOf(`hour`),endsAt:null,location:``,description:``,imageUrl:``}:{title:e.title,startsAt:(0,v.default)(e.startsAt),endsAt:e.endsAt?(0,v.default)(e.endsAt):null,location:e.location??``,description:e.description??``,imageUrl:e.imageUrl}),r(e)},c=async()=>{let i=await o.validateFields(),s={title:i.title.trim(),startsAt:i.startsAt.toISOString(),endsAt:i.endsAt?i.endsAt.toISOString():null,location:i.location.trim()||null,description:i.description.trim()||null,imageUrl:i.imageUrl};a(!0);try{n===`new`?await e.createEvent(s):n&&await e.updateEvent(n.id,s),u.message.success(`Đã lưu sự kiện`),r(null),t.reload()}catch(e){u.message.error(x(e,`FEED_EVENT_INVALID`)?`Thông tin sự kiện không hợp lệ`:`Không lưu được sự kiện`)}finally{a(!1)}},l=async n=>{try{await e.deleteEvent(n.id),u.message.success(`Đã xoá sự kiện`),t.reload()}catch{u.message.error(`Không xoá được sự kiện`)}};return(0,p.jsxs)(`div`,{className:`med-feed-wide med-feed-events-admin`,children:[(0,p.jsx)(Rk,{title:`Sự kiện`,description:`Khung bên phải bảng tin hiện sự kiện mới tạo gần nhất`,extra:(0,p.jsx)(u.Button,{type:`primary`,icon:(0,p.jsx)(h.PlusOutlined,{}),onClick:()=>s(`new`),children:`Thêm sự kiện`})}),(0,p.jsx)(u.Table,{rowKey:`id`,columns:[{title:`Ảnh`,dataIndex:`imageUrl`,width:90,render:e=>(0,p.jsx)(`img`,{src:e,alt:``,className:`med-feed-events-admin__thumb`})},{title:`Sự kiện`,dataIndex:`title`},{title:`Thời gian`,width:260,render:(e,t)=>Ch(t.startsAt,t.endsAt)},{title:`Địa điểm`,dataIndex:`location`,width:180,render:e=>e??``},{title:``,fixed:`right`,width:100,render:(e,t)=>(0,p.jsxs)(u.Space,{size:8,children:[(0,p.jsx)(u.Button,{icon:(0,p.jsx)(h.EditOutlined,{}),"aria-label":`Sửa`,onClick:()=>s(t)}),(0,p.jsx)(u.Popconfirm,{title:`Xoá sự kiện này?`,okText:`Xoá`,cancelText:`Huỷ`,okButtonProps:{danger:!0},onConfirm:()=>l(t),children:(0,p.jsx)(u.Button,{danger:!0,icon:(0,p.jsx)(h.DeleteOutlined,{}),"aria-label":`Xoá`})})]})}],dataSource:t.data??[],loading:t.loading,pagination:!1,scroll:{x:`max-content`}}),(0,p.jsx)(u.Modal,{open:n!==null,title:(0,p.jsxs)(`div`,{className:`med-feed-events-form__head`,children:[(0,p.jsx)(`strong`,{children:n===`new`?`Thêm sự kiện`:`Sửa sự kiện`}),(0,p.jsx)(`span`,{children:`Hiện ở khung bên phải bảng tin cho mọi người`})]}),okText:n===`new`?`Thêm sự kiện`:`Lưu thay đổi`,cancelText:`Huỷ`,confirmLoading:i,width:560,centered:!0,wrapClassName:`med-feed-portal med-feed-events-form-modal`,maskStyle:{background:`rgba(11, 28, 48, 0.5)`,backdropFilter:`blur(4px)`},onOk:()=>void c(),onCancel:()=>r(null),destroyOnClose:!0,children:(0,p.jsxs)(u.Form,{form:o,layout:`vertical`,preserve:!1,requiredMark:!1,children:[(0,p.jsx)(u.Form.Item,{name:`imageUrl`,label:`Ảnh bìa`,rules:[{required:!0,message:`Cần có ảnh bìa`}],children:(0,p.jsx)(Vk,{aspectRatio:`16 / 9`})}),(0,p.jsx)(u.Form.Item,{name:`title`,label:`Tên sự kiện`,rules:[{required:!0,whitespace:!0,message:`Nhập tên sự kiện`}],children:(0,p.jsx)(u.Input,{size:`large`,maxLength:120,placeholder:`Ví dụ: Hội thao Meditech 2026`})}),(0,p.jsxs)(`div`,{className:`med-feed-events-form__row`,children:[(0,p.jsx)(u.Form.Item,{name:`startsAt`,label:`Bắt đầu`,rules:[{required:!0,message:`Chọn giờ bắt đầu`}],children:(0,p.jsx)(u.DatePicker,{size:`large`,showTime:!0,format:Hk,style:{width:`100%`}})}),(0,p.jsx)(u.Form.Item,{name:`endsAt`,label:`Kết thúc`,dependencies:[`startsAt`],rules:[({getFieldValue:e})=>({validator:(t,n)=>{let r=e(`startsAt`);return n&&r&&n.isBefore(r)?Promise.reject(Error(`Giờ kết thúc phải sau giờ bắt đầu`)):Promise.resolve()}})],children:(0,p.jsx)(u.DatePicker,{size:`large`,showTime:!0,format:Hk,placeholder:`Không bắt buộc`,style:{width:`100%`}})})]}),(0,p.jsx)(u.Form.Item,{name:`location`,label:`Địa điểm`,children:(0,p.jsx)(u.Input,{size:`large`,maxLength:200,placeholder:`Ví dụ: Sân vận động Quân khu 7`})}),(0,p.jsx)(u.Form.Item,{name:`description`,label:`Mô tả ngắn`,children:(0,p.jsx)(u.Input.TextArea,{rows:4,maxLength:2e3,showCount:!0,placeholder:`Giới thiệu nội dung, đối tượng tham gia...`})})]})})]})}var Wk=300;function Gk({value:e,onChange:t,placeholder:n=`Tất cả tác giả`}){let{api:r}=D(),[i,a]=(0,f.useState)([]),[o,s]=(0,f.useState)(!1),c=(0,f.useRef)();return(0,f.useEffect)(()=>()=>clearTimeout(c.current),[]),(0,p.jsx)(u.Select,{showSearch:!0,allowClear:!0,value:e,placeholder:n,suffixIcon:(0,p.jsx)(h.UserOutlined,{}),filterOption:!1,onSearch:e=>{clearTimeout(c.current),e.trim()&&(s(!0),c.current=setTimeout(()=>{r.searchUsers(e).then(e=>{a(e),s(!1)},()=>s(!1))},Wk))},onChange:e=>t(e),notFoundContent:o?(0,p.jsx)(u.Spin,{size:`small`}):`Gõ tên hoặc mã nhân viên`,style:{minWidth:200},className:`med-feed-author-select`,options:i.map(e=>({value:e.id,label:e.departmentName?`${e.fullName} · ${e.departmentName}`:e.fullName}))})}var Kk={"7d":`7 ngày gần nhất`,"30d":`30 ngày gần nhất`,"90d":`90 ngày gần nhất`,"this-month":`Tháng này`,"this-year":`Năm nay`};function qk(e){let t=String(e.getMonth()+1).padStart(2,`0`),n=String(e.getDate()).padStart(2,`0`);return`${e.getFullYear()}-${t}-${n}`}function Jk(e){return typeof e==`object`}function Yk(e,t=new Date){if(Jk(e))return e;let n=e,r=new Date(t);return n===`this-month`?r.setDate(1):n===`this-year`?r.setMonth(0,1):r.setDate(t.getDate()-(Number.parseInt(n,10)-1)),{from:qk(r),to:qk(t)}}var Xk=`YYYY-MM-DD`;function Zk({value:e,onChange:t}){let n=Yk(e),r=(0,f.useMemo)(()=>Object.fromEntries(Object.keys(Kk).map(e=>{let{from:t,to:n}=Yk(e);return[Kk[e],[(0,v.default)(t,Xk),(0,v.default)(n,Xk)]]})),[]);return(0,p.jsx)(`span`,{className:`med-feed-date-range med-feed-pill-fields`,children:(0,p.jsx)(u.DatePicker.RangePicker,{value:[(0,v.default)(n.from,Xk),(0,v.default)(n.to,Xk)],format:`DD/MM/YYYY`,allowClear:!1,ranges:r,placeholder:[`Từ ngày`,`Đến ngày`],disabledDate:e=>e.isAfter((0,v.default)(),`day`),onChange:e=>{let[n,r]=e??[];n&&r&&t({from:n.format(Xk),to:r.format(Xk)})}})})}function Qk({post:e,onOpen:t}){let n=new Map(e.mentionedUsers.map(e=>[e.id,e.fullName])),r=e.media.find(e=>e.kind===`IMAGE`);return(0,p.jsxs)(`button`,{type:`button`,className:`med-feed-table-post`,onClick:()=>t(e),children:[r?(0,p.jsx)(`img`,{src:r.fileUrl,alt:``,referrerPolicy:`no-referrer`}):(0,p.jsx)(`span`,{className:`med-feed-table-post__placeholder`,"aria-hidden":!0,children:e.media.length>0?`📎`:`Aa`}),(0,p.jsxs)(`span`,{className:`med-feed-table-post__body`,children:[(0,p.jsx)(u.Typography.Paragraph,{ellipsis:{rows:2},className:`med-feed-table-post__text`,children:ke(e.content,160,n)||(r?`[Hình ảnh]`:`[Tài liệu]`)}),(0,p.jsxs)(`span`,{className:`med-feed-table-post__meta`,children:[Xp(e.createdAt),e.media.length>0&&` · ${e.media.length} tệp đính kèm`]})]})]})}function $k({post:e,onClose:t,onChanged:n,onRemoved:r,onEdit:i,readOnly:a=!1}){let{api:o}=D(),[s,c]=(0,f.useState)(!1),l=async(e,r)=>{c(!0);try{n(await e()),u.message.success(r),t()}catch{u.message.error(`Thao tác không thành công, bài có thể đã được người khác xử lý`)}finally{c(!1)}},d=e&&(0,p.jsxs)(u.Space,{children:[(0,p.jsx)(ch,{post:e,labelled:!0,onRemoved:e=>{r(e),t()}}),e.status===`PENDING`&&(0,p.jsx)(u.Button,{type:`primary`,loading:s,onClick:()=>void l(()=>o.approvePost(e.id),`Đã duyệt bài, chờ phát hành`),children:`Duyệt`}),e.status===`APPROVED`&&(0,p.jsx)(u.Button,{type:`primary`,loading:s,onClick:()=>void l(()=>o.publishPost(e.id),`Đã phát hành bài lên bảng tin`),children:`Phát Hành`}),e.status===`PUBLISHED`&&(e.commentsLocked?(0,p.jsx)(u.Button,{loading:s,onClick:()=>void l(()=>o.unlockComments(e.id),`Đã mở bình luận`),children:`Mở bình luận`}):(0,p.jsx)(u.Button,{loading:s,onClick:()=>void l(()=>o.lockComments(e.id),`Đã khoá bình luận`),children:`Khoá bình luận`})),e.status===`PUBLISHED`&&(0,p.jsx)(u.Button,{loading:s,onClick:()=>void l(()=>e.pinnedAt?o.unpinPost(e.id):o.pinPost(e.id),e.pinnedAt?`Đã bỏ ghim bài`:`Đã ghim bài lên đầu bảng tin`),children:e.pinnedAt?`Bỏ ghim`:`Ghim lên đầu`}),e.status===`PUBLISHED`&&(0,p.jsx)(u.Button,{danger:!0,loading:s,onClick:()=>void l(()=>o.unpublishPost(e.id),`Đã gỡ bài khỏi bảng tin`),children:`Gỡ bài`}),e.status===`UNPUBLISHED`&&(0,p.jsxs)(p.Fragment,{children:[i&&(0,p.jsx)(u.Button,{disabled:s,onClick:()=>{i(e),t()},children:`Sửa`}),(0,p.jsx)(u.Button,{type:`primary`,loading:s,onClick:()=>void l(()=>o.submitPost(e.id),`Đã gửi duyệt lại`),children:`Gửi duyệt lại`})]})]});return(0,p.jsxs)(u.Drawer,{title:`Xem bài viết`,width:720,open:e!==null,onClose:t,extra:a?void 0:d,destroyOnClose:!0,className:`med-feed-portal med-feed-review-drawer`,children:[e&&(0,p.jsx)(hh,{post:e,mode:`preview`}),e&&!a&&!e.commentsLocked&&e.commentCount>0&&(0,p.jsxs)(`section`,{className:`med-feed-review-drawer__comments`,children:[(0,p.jsx)(u.Typography.Title,{level:5,children:`Bình luận`}),(0,p.jsx)(om,{post:e,moderate:!0,onCommentCountChange:t=>n({...e,commentCount:e.commentCount+t})})]})]})}var eA=10,tA=[{key:`PENDING`,label:`Chờ duyệt`,hint:`Cần xử lý`,tone:`pending`},{key:`APPROVED`,label:`Đã duyệt`,hint:`Chờ phát hành`,tone:`approved`},{key:`PUBLISHED`,label:`Đang phát hành`,hint:`Đang hiển thị`,tone:`published`},{key:`UNPUBLISHED`,label:`Đã gỡ`,hint:`Gỡ khỏi bảng tin`,tone:`unpublished`},{key:`DELETED`,label:`Đã xoá`,hint:`Lưu cho báo cáo`,tone:`deleted`},{key:`ALL`,label:`Tất cả`,hint:`Mọi trạng thái`,tone:`all`}];function nA(){let{api:e}=D(),[t,n]=(0,f.useState)(`30d`),[r,i]=(0,f.useState)(`PENDING`),[a,o]=(0,f.useState)(),[s,c]=(0,f.useState)(``),[l,d]=(0,f.useState)(``),[m,g]=(0,f.useState)(1),[_,v]=(0,f.useState)([]),[y,b]=(0,f.useState)(null),[x,S]=(0,f.useState)(null),[C,w]=(0,f.useState)(null),T=(0,f.useMemo)(()=>Yk(t),[t]),ee=hp((0,f.useCallback)(()=>e.listManagePosts({...T,status:r===`ALL`?void 0:r,authorId:a,q:s||void 0,page:m,pageSize:eA}),[e,T,r,a,s,m]),JSON.stringify({range:T,status:r,authorId:a,q:s,page:m})),te=hp((0,f.useCallback)(()=>e.getManageCounts(T),[e,T]),JSON.stringify(T)),E=()=>{v([]),ee.reload(),te.reload()};(0,f.useEffect)(()=>{let e=l.trim();if(e===s)return;let t=setTimeout(()=>{c(e),g(1),v([])},350);return()=>clearTimeout(t)},[l,s]);let ne=e=>t=>{e(t),g(1),v([])},re=async(e,t,n)=>{S(e.id);try{await t(),u.message.success(n),E()}catch{u.message.error(`Thao tác không thành công, bài có thể đã được người khác xử lý`)}finally{S(null)}},ie=async()=>{try{await e.approvePosts(_),u.message.success(`Đã duyệt ${_.length} bài viết, chờ phát hành`),E()}catch{u.message.error(`Không duyệt được các bài đã chọn`)}},ae=(e,t,n,r,i=`default`)=>(0,p.jsx)(u.Tooltip,{title:t,children:(0,p.jsx)(u.Button,{size:`small`,icon:n,"aria-label":t,loading:x===e.id&&i!=="default",className:`med-feed-manage__action med-feed-manage__action--${i}`,onClick:r})});return(0,p.jsxs)(`div`,{className:`med-feed-wide med-feed-manage`,children:[(0,p.jsx)(Rk,{title:`Trung tâm duyệt bài viết`,description:`Duyệt, phát hành, gỡ và theo dõi tương tác của mọi bài viết trên bảng tin`,extra:(0,p.jsx)(Lk,{onSaved:E})}),(0,p.jsxs)(`section`,{className:`med-feed-manage__panel`,children:[(0,p.jsx)(`div`,{className:`med-feed-manage__tabs`,role:`tablist`,"aria-label":`Lọc theo trạng thái`,children:tA.map(e=>{let t=e.key===`ALL`?te.data?te.data.PENDING+te.data.APPROVED+te.data.PUBLISHED+te.data.UNPUBLISHED+te.data.DELETED:void 0:te.data?.[e.key],n=r===e.key;return(0,p.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n,title:e.hint,className:`med-feed-manage__tab med-feed-manage__tab--${e.tone}${n?` med-feed-manage__tab--active`:``}`,onClick:()=>ne(i)(e.key),children:[e.label,(0,p.jsx)(`span`,{className:`med-feed-manage__tab-count`,children:t===void 0?`–`:A(t)})]},e.key)})}),(0,p.jsxs)(`div`,{className:`med-feed-manage__toolbar med-feed-pill-fields`,children:[(0,p.jsx)(u.Input,{allowClear:!0,value:l,prefix:(0,p.jsx)(h.SearchOutlined,{}),placeholder:`Tìm theo nội dung bài viết…`,className:`med-feed-manage__search`,onPressEnter:()=>ne(c)(l.trim()),onChange:e=>{d(e.target.value),e.target.value||ne(c)(``)}}),(0,p.jsx)(Zk,{value:t,onChange:ne(n)}),(0,p.jsx)(Gk,{value:a,onChange:ne(o)}),(s||a||JSON.stringify(T)!==JSON.stringify(Yk(`30d`)))&&(0,p.jsx)(u.Button,{type:`link`,icon:(0,p.jsx)(h.CloseCircleOutlined,{}),className:`med-feed-manage__clear`,onClick:()=>{d(``),c(``),o(void 0),n(`30d`),g(1),v([])},children:`Xoá bộ lọc`})]}),_.length>0&&(0,p.jsxs)(`div`,{className:`med-feed-manage__bulk`,children:[(0,p.jsxs)(`span`,{children:[`Đã chọn `,(0,p.jsx)(`strong`,{children:_.length}),` bài chờ duyệt`]}),(0,p.jsxs)(u.Space,{children:[(0,p.jsx)(u.Button,{onClick:()=>v([]),children:`Bỏ chọn`}),(0,p.jsx)(u.Button,{type:`primary`,icon:(0,p.jsx)(h.CheckOutlined,{}),onClick:()=>void ie(),children:`Duyệt hàng loạt`})]})]}),(0,p.jsx)(u.Table,{className:`med-feed-manage-table`,rowKey:`id`,columns:[{title:`Bài viết`,key:`content`,render:(e,t)=>(0,p.jsx)(Qk,{post:t,onOpen:b})},{title:`Tác giả`,key:`author`,width:220,render:(e,t)=>(0,p.jsxs)(`span`,{className:`med-feed-table-author`,children:[(0,p.jsx)(mp,{user:t.author,size:32}),(0,p.jsxs)(`span`,{children:[(0,p.jsx)(`strong`,{children:t.author.fullName}),t.author.departmentName&&(0,p.jsx)(`span`,{children:t.author.departmentName})]})]})},{title:`Trạng thái`,key:`status`,width:130,render:(e,t)=>(0,p.jsxs)(`span`,{className:`med-feed-table-status`,children:[(0,p.jsx)(dh,{status:t.status,short:!0}),t.pinnedAt&&t.status===`PUBLISHED`&&(0,p.jsx)(uh,{})]})},{title:`Ngày tạo`,key:`createdAt`,width:150,render:(e,t)=>(0,p.jsx)(`span`,{className:`med-feed-table-date`,children:Xp(t.createdAt)})},{title:`Tương tác`,key:`engagement`,width:220,render:(e,t)=>(0,p.jsxs)(`span`,{className:`med-feed-table-engagement`,children:[(0,p.jsxs)(`span`,{children:[(0,p.jsx)(h.LikeOutlined,{}),` `,A(t.reactionCount)]}),(0,p.jsxs)(`span`,{children:[(0,p.jsx)(h.CommentOutlined,{}),` `,A(t.commentCount)]}),(0,p.jsxs)(`span`,{children:[(0,p.jsx)(h.ShareAltOutlined,{}),` `,A(t.shareCount)]})]})},{title:`Thao tác`,key:`actions`,fixed:`right`,width:180,align:`right`,render:(t,n)=>(0,p.jsxs)(u.Space,{size:6,children:[n.status===`PENDING`&&ae(n,`Duyệt`,(0,p.jsx)(h.CheckOutlined,{}),()=>void re(n,()=>e.approvePost(n.id),`Đã duyệt bài, chờ phát hành`),`primary`),n.status===`APPROVED`&&ae(n,`Phát Hành`,(0,p.jsx)(h.CloudUploadOutlined,{}),()=>void re(n,()=>e.publishPost(n.id),`Đã phát hành bài lên bảng tin`),`primary`),n.status===`PUBLISHED`&&ae(n,n.pinnedAt?`Bỏ ghim`:`Ghim lên đầu`,n.pinnedAt?(0,p.jsx)(h.PushpinFilled,{}):(0,p.jsx)(h.PushpinOutlined,{}),()=>void re(n,()=>n.pinnedAt?e.unpinPost(n.id):e.pinPost(n.id),n.pinnedAt?`Đã bỏ ghim bài`:`Đã ghim bài lên đầu bảng tin`)),n.status===`PUBLISHED`&&ae(n,`Gỡ bài`,(0,p.jsx)(h.EyeInvisibleOutlined,{}),()=>void re(n,()=>e.unpublishPost(n.id),`Đã gỡ bài khỏi bảng tin`),`danger`),n.status===`UNPUBLISHED`&&(0,p.jsxs)(p.Fragment,{children:[ae(n,`Sửa bài`,(0,p.jsx)(h.EditOutlined,{}),()=>w(n)),ae(n,`Gửi duyệt lại`,(0,p.jsx)(h.SendOutlined,{}),()=>void re(n,()=>e.submitPost(n.id),`Đã gửi duyệt lại`),`primary`),ae(n,`Xoá bài`,(0,p.jsx)(h.DeleteOutlined,{}),()=>ah(()=>re(n,()=>e.deletePost(n.id),`Đã xoá bài viết`)))]}),ae(n,`Xem chi tiết`,(0,p.jsx)(h.EyeOutlined,{}),()=>b(n))]})}],dataSource:ee.data?.items??[],loading:ee.loading,rowSelection:{selectedRowKeys:_,onChange:e=>v(e),getCheckboxProps:e=>({disabled:e.status!==`PENDING`})},locale:{emptyText:ee.error?`Không tải được danh sách bài`:`Không có bài viết nào`},scroll:{x:1040},pagination:{current:m,pageSize:eA,total:ee.data?.total??0,showSizeChanger:!1,showTotal:(e,[t,n])=>`Hiển thị ${t}–${n} trong ${A(e)} bài viết`,onChange:e=>{g(e),v([])}}})]}),(0,p.jsx)($k,{post:y,onClose:()=>b(null),onChanged:E,onRemoved:E,onEdit:w}),(0,p.jsx)(Ik,{open:C!==null,initialPost:C??void 0,onClose:()=>w(null),onSaved:E},C?.id??`closed`)]})}var rA=/^https?:\/\/\S+$/;function iA(){let{api:e}=D(),t=hp((0,f.useCallback)(()=>e.getRightBanner(),[e]),`banner-settings`),[n]=u.Form.useForm(),[r,i]=(0,f.useState)(!1),a=t.data?.imageUrl?t.data:null;(0,f.useEffect)(()=>{t.data&&n.setFieldsValue({imageUrl:t.data.imageUrl??``,linkUrl:t.data.linkUrl??``})},[t.data,n]);let o=async()=>{let r=await n.validateFields();i(!0);try{await e.setRightBanner({imageUrl:r.imageUrl,linkUrl:r.linkUrl.trim()||null}),u.message.success(`Đã lưu banner`),t.reload()}catch{u.message.error(`Không lưu được banner`)}finally{i(!1)}},s=async()=>{try{await e.clearRightBanner(),n.setFieldsValue({imageUrl:``,linkUrl:``}),u.message.success(`Đã gỡ banner`),t.reload()}catch{u.message.error(`Không gỡ được banner`)}};return(0,p.jsxs)(`div`,{className:`med-feed-banner-settings`,children:[(0,p.jsx)(Rk,{title:`Banner bên phải`,description:`Ảnh quảng cáo hiện dưới khung sự kiện ở cột phải bảng tin`}),(0,p.jsx)(`section`,{className:`med-feed-banner-settings__panel`,children:(0,p.jsxs)(u.Form,{form:n,layout:`vertical`,requiredMark:!1,children:[(0,p.jsx)(u.Form.Item,{name:`imageUrl`,label:`Ảnh banner`,extra:`Nên dùng ảnh dọc; ảnh hiện rộng đúng bằng cột phải và giữ nguyên tỉ lệ.`,rules:[{required:!0,message:`Cần chọn ảnh banner`}],children:(0,p.jsx)(Vk,{aspectRatio:`4 / 7`,maxWidth:280})}),(0,p.jsx)(u.Form.Item,{name:`linkUrl`,label:`Đường dẫn khi bấm vào (không bắt buộc)`,rules:[{pattern:rA,message:`Đường dẫn phải bắt đầu bằng http:// hoặc https://`}],children:(0,p.jsx)(u.Input,{size:`large`,maxLength:2048,placeholder:`https://...`})}),(0,p.jsxs)(`div`,{className:`med-feed-banner-settings__actions`,children:[(0,p.jsx)(u.Button,{type:`primary`,loading:r,onClick:()=>void o(),children:`Lưu banner`}),a&&(0,p.jsx)(u.Popconfirm,{title:`Gỡ banner này?`,okText:`Gỡ`,cancelText:`Huỷ`,okButtonProps:{danger:!0},onConfirm:()=>s(),children:(0,p.jsx)(u.Button,{danger:!0,icon:(0,p.jsx)(h.DeleteOutlined,{}),children:`Gỡ banner`})})]})]})})]})}function aA(){let{basePath:e}=D(),t=[{to:`${`${e.replace(/\/+$/,``)}/settings`}/banner`,label:`Banner`}];return(0,p.jsxs)(`div`,{className:`med-feed-wide med-feed-settings`,children:[(0,p.jsx)(`nav`,{className:`med-feed-settings__tabs`,"aria-label":`Cấu hình`,children:t.map(e=>(0,p.jsx)(m.NavLink,{to:e.to,className:({isActive:e})=>e?`med-feed-settings__tab med-feed-settings__tab--active`:`med-feed-settings__tab`,children:e.label},e.to))}),(0,p.jsxs)(m.Routes,{children:[(0,p.jsx)(m.Route,{index:!0,element:(0,p.jsx)(m.Navigate,{to:`banner`,replace:!0})}),(0,p.jsx)(m.Route,{path:`banner`,element:(0,p.jsx)(iA,{})})]})]})}var oA={ZALO:`Zalo`,FACEBOOK:`Facebook`,CHAT:`Chat`,LINK:`Liên kết`};function sA({title:e,value:t,icon:n,tone:r,detail:i,loading:a}){return(0,p.jsxs)(`div`,{className:`med-feed-kpi med-feed-kpi--${r}`,children:[(0,p.jsx)(`span`,{className:`med-feed-kpi__icon`,"aria-hidden":!0,children:n}),(0,p.jsxs)(`div`,{className:`med-feed-kpi__body`,children:[(0,p.jsx)(`span`,{className:`med-feed-kpi__title`,children:e}),a?(0,p.jsx)(u.Skeleton.Input,{active:!0,size:`small`,className:`med-feed-kpi__skeleton`}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`span`,{className:`med-feed-kpi__value`,children:A(t??0)}),i&&(0,p.jsx)(`span`,{className:`med-feed-kpi__detail`,children:i})]})]})]})}function cA({overview:e,loading:t}){let n=Ae.filter(t=>(e?.reactionsByType[t]??0)>0),r=e?.postsByStatus??{},i=[`ZALO`,`FACEBOOK`,`CHAT`,`LINK`].filter(t=>(e?.sharesByChannel?.[t]??0)>0);return(0,p.jsxs)(`div`,{className:`med-feed-kpis`,children:[(0,p.jsx)(sA,{title:`Bài viết`,tone:`posts`,value:e?.postCount,icon:(0,p.jsx)(h.FileTextOutlined,{}),loading:t,detail:`${A(r.PUBLISHED??0)} đang phát hành · ${A(r.UNPUBLISHED??0)} đã gỡ · ${A(r.PENDING??0)} chờ duyệt`}),(0,p.jsx)(sA,{title:`Reaction`,tone:`reactions`,value:e?.reactionTotal,icon:(0,p.jsx)(h.LikeFilled,{}),loading:t,detail:n.length>0?n.map(t=>`${Vm[t].label} ${A(e?.reactionsByType[t]??0)}`).join(` · `):`Chưa có cảm xúc nào`}),(0,p.jsx)(sA,{title:`Bình luận`,tone:`comments`,value:e?.commentCount,icon:(0,p.jsx)(h.CommentOutlined,{}),loading:t,detail:`${A(e?.rootCommentCount??0)} bình luận · ${A(e?.replyCount??0)} trả lời`}),(0,p.jsx)(sA,{title:`Chia sẻ`,tone:`shares`,value:e?.shareTotal,icon:(0,p.jsx)(h.ShareAltOutlined,{}),loading:t,detail:i.length>0?i.map(t=>`${oA[t]} ${A(e?.sharesByChannel?.[t]??0)}`).join(` · `):`Chưa có lượt chia sẻ`})]})}var lA=[{value:`day`,label:`Ngày`},{value:`week`,label:`Tuần`},{value:`month`,label:`Tháng`}];function uA(e){let t=String(e.getMonth()+1).padStart(2,`0`);return`${e.getFullYear()}-${t}-${String(e.getDate()).padStart(2,`0`)}`}function dA(e,t=new Date){let n=new Date(t);return e===`week`&&n.setDate(t.getDate()-(t.getDay()+6)%7),e===`month`&&n.setDate(1),{from:uA(n),to:uA(t)}}function fA({value:e,onChange:t}){let n=Yk(e),r=lA.find(({value:e})=>{let t=dA(e);return t.from===n.from&&t.to===n.to})?.value;return(0,p.jsx)(u.Radio.Group,{className:`med-feed-segmented`,optionType:`button`,options:lA,value:r,onChange:e=>t(dA(e.target.value))})}var pA=10,mA=[{value:`total`,label:`Tổng tương tác`},{value:`reactions`,label:`Reaction`},{value:`comments`,label:`Bình luận`}];function hA({range:e}){let{api:t}=D(),[n,r]=(0,f.useState)(`total`),[i,a]=(0,f.useState)({from:e.from,to:e.to}),[o,s]=(0,f.useState)(``),[c,l]=(0,f.useState)(``),[d,m]=(0,f.useState)(null),g=(0,f.useMemo)(()=>({...e,...Yk(i),...c?{q:c}:{}}),[e,i,c]),_=hp((0,f.useCallback)(()=>t.getTopPosts({...g,sortBy:n,limit:pA}),[t,g,n]),`${JSON.stringify(g)}|${n}`);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`med-feed-report-toolbar med-feed-pill-fields`,children:[(0,p.jsx)(u.Input,{allowClear:!0,value:o,prefix:(0,p.jsx)(h.SearchOutlined,{}),placeholder:`Tìm theo nội dung bài viết… (Enter để tìm)`,className:`med-feed-report-toolbar__search`,onPressEnter:()=>l(o.trim()),onChange:e=>{s(e.target.value),e.target.value||l(``)}}),(0,p.jsx)(fA,{value:i,onChange:a}),(0,p.jsx)(Zk,{value:i,onChange:a}),(0,p.jsx)(u.Select,{value:n,onChange:r,options:mA,style:{minWidth:170},"aria-label":`Xếp theo`})]}),(0,p.jsx)(u.Table,{className:`med-feed-manage-table`,rowKey:`id`,pagination:!1,loading:_.loading,dataSource:_.data??[],locale:{emptyText:_.error?`Không tải được danh sách`:c?`Không có bài nào khớp`:`Chưa có bài trong khoảng này`},scroll:{x:900},columns:[{title:`#`,key:`rank`,width:56,render:(e,t,n)=>(0,p.jsx)(`span`,{className:n<3?`med-feed-top-rank med-feed-top-rank--top`:`med-feed-top-rank`,children:n+1})},{title:`Bài viết`,key:`post`,render:(e,t)=>(0,p.jsx)(Qk,{post:t,onOpen:m})},{title:`Tương tác`,key:`engagement`,width:280,render:(e,t)=>(0,p.jsxs)(`span`,{className:`med-feed-table-engagement`,children:[(0,p.jsxs)(`span`,{title:`Reaction`,children:[(0,p.jsx)(h.LikeOutlined,{}),` `,A(t.reactionCount)]}),(0,p.jsxs)(`span`,{title:`Bình luận`,children:[(0,p.jsx)(h.CommentOutlined,{}),` `,A(t.commentCount)]}),(0,p.jsxs)(`span`,{title:`Chia sẻ`,children:[(0,p.jsx)(h.ShareAltOutlined,{}),` `,A(t.shareCount)]})]})},{title:`Tổng tương tác`,key:`total`,width:130,align:`right`,render:(e,t)=>(0,p.jsx)(`strong`,{children:A(t.reactionCount+t.commentCount+t.shareCount)})},{title:``,key:`actions`,fixed:`right`,width:64,align:`right`,render:(e,t)=>(0,p.jsx)(u.Tooltip,{title:`Xem chi tiết`,children:(0,p.jsx)(u.Button,{size:`small`,icon:(0,p.jsx)(h.EyeOutlined,{}),"aria-label":`Xem chi tiết`,className:`med-feed-manage__action`,onClick:()=>m(t)})})}]}),(0,p.jsx)($k,{post:d,onClose:()=>m(null),onChanged:()=>_.reload(),onRemoved:()=>_.reload(),readOnly:!0})]})}var gA=10;function _A({range:e}){let{api:t}=D(),[n,r]=(0,f.useState)({from:e.from,to:e.to}),[i,a]=(0,f.useState)(),[o,s]=(0,f.useState)(null),c=(0,f.useMemo)(()=>({...e,...Yk(n),...i?{userId:i}:{}}),[e,n,i]),l=hp((0,f.useCallback)(()=>t.getTopUsers({...c,limit:gA}),[t,c]),JSON.stringify(c));return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`med-feed-report-toolbar med-feed-pill-fields`,children:[(0,p.jsx)(Gk,{value:i,onChange:a,placeholder:`Tất cả nhân viên`}),(0,p.jsx)(fA,{value:n,onChange:r}),(0,p.jsx)(Zk,{value:n,onChange:r})]}),(0,p.jsx)(u.Table,{className:`med-feed-manage-table`,rowKey:e=>e.user.id,pagination:!1,loading:l.loading,dataSource:l.data??[],locale:{emptyText:l.error?`Không tải được số liệu`:`Chưa có hoạt động`},scroll:{x:1200},columns:[{title:`#`,key:`rank`,width:56,render:(e,t,n)=>(0,p.jsx)(`span`,{className:!i&&n<3?`med-feed-top-rank med-feed-top-rank--top`:`med-feed-top-rank`,children:n+1})},{title:`Nhân viên`,key:`user`,width:240,render:(e,t)=>(0,p.jsxs)(`span`,{className:`med-feed-report-person`,children:[(0,p.jsx)(mp,{user:t.user,size:32}),(0,p.jsxs)(`span`,{children:[(0,p.jsx)(`strong`,{children:t.user.fullName}),t.user.departmentName&&(0,p.jsx)(`span`,{children:t.user.departmentName})]})]})},{title:`Bài tương tác nhiều nhất`,key:`topPost`,render:(e,t)=>t.topPost?(0,p.jsx)(Qk,{post:t.topPost.post,onOpen:s}):(0,p.jsx)(`span`,{className:`med-feed-report-muted`,children:`—`})},{title:`Reaction`,dataIndex:`reactions`,width:100,align:`right`,render:A},{title:`Bình luận`,dataIndex:`comments`,width:100,align:`right`,render:A},{title:`Chia sẻ`,dataIndex:`shares`,width:90,align:`right`,render:A},{title:`Tổng tương tác`,dataIndex:`total`,width:130,align:`right`,render:e=>(0,p.jsx)(`strong`,{children:A(e)})}]}),(0,p.jsx)($k,{post:o,onClose:()=>s(null),onChanged:()=>l.reload(),onRemoved:()=>l.reload(),readOnly:!0})]})}var vA=[`#7c3aed`,`#2563eb`,`#0d9488`],yA=[{label:`Ngày`,value:`day`},{label:`Tuần`,value:`week`},{label:`Tháng`,value:`month`}];function bA(e,t){let[n,r,i]=e.slice(0,10).split(`-`);return t===`month`?`${r}/${n}`:t===`week`?`Tuần ${i}/${r}`:`${i}/${r}`}function xA({range:e}){let{api:t}=D(),[n,r]=(0,f.useState)(`day`),[i,a]=(0,f.useState)({from:e.from,to:e.to}),o=(0,f.useMemo)(()=>({...e,...Yk(i)}),[e,i]),[s,c]=(0,f.useState)(!1),l=hp((0,f.useCallback)(()=>t.getReportsTimeseries({...o,groupBy:n}),[t,o,n]),`${JSON.stringify(o)}|${n}`),d=l.data??[],m=d.map(e=>bA(e.bucket,n)),h={chart:{type:`line`,toolbar:{show:!1},zoom:{enabled:!1},fontFamily:`inherit`},colors:vA,stroke:{width:2,curve:`smooth`},markers:{size:0,hover:{size:5},strokeColors:`#ffffff`,strokeWidth:2},dataLabels:{enabled:!1},legend:{position:`top`,horizontalAlign:`right`,fontSize:`13px`},grid:{borderColor:`#eef0f4`,strokeDashArray:4},xaxis:{categories:m,tickAmount:Math.min(m.length,10),labels:{style:{colors:`#65676b`}},axisBorder:{show:!1},crosshairs:{show:!0}},yaxis:{min:0,forceNiceScale:!0,labels:{formatter:e=>A(Math.round(e))}},tooltip:{shared:!0,intersect:!1,y:{formatter:e=>A(e)}}};return(0,p.jsx)(u.Card,{bordered:!1,className:`med-feed-report-panel`,title:`Xu hướng tương tác`,extra:(0,p.jsxs)(u.Space,{wrap:!0,children:[(0,p.jsx)(Zk,{value:i,onChange:a}),(0,p.jsx)(u.Radio.Group,{size:`small`,className:`med-feed-segmented`,optionType:`button`,options:yA,value:n,onChange:e=>r(e.target.value)}),(0,p.jsx)(u.Button,{size:`small`,type:`text`,onClick:()=>c(!s),children:s?`Biểu đồ`:`Bảng số liệu`})]}),children:l.loading?(0,p.jsx)(u.Skeleton,{active:!0,paragraph:{rows:6}}):d.length===0?(0,p.jsx)(u.Empty,{description:l.error?`Không tải được số liệu`:`Chưa có tương tác trong khoảng này`}):s?(0,p.jsx)(u.Table,{className:`med-feed-manage-table`,rowKey:`bucket`,size:`small`,pagination:!1,scroll:{y:320},dataSource:d,columns:[{title:`Thời gian`,key:`bucket`,render:(e,t)=>bA(t.bucket,n)},{title:`Reaction`,dataIndex:`reactions`,align:`right`,render:A},{title:`Bình luận`,dataIndex:`comments`,align:`right`,render:A}]}):(0,p.jsx)(y.default,{type:`line`,height:320,options:h,series:[{name:`Reaction`,data:d.map(e=>e.reactions)},{name:`Bình luận`,data:d.map(e=>e.comments)}]})})}function SA(){let{api:e}=D(),[t,n]=(0,f.useState)(`30d`),r=(0,f.useMemo)(()=>Yk(t),[t]),i=hp((0,f.useCallback)(()=>e.getReportsOverview(r),[e,r]),JSON.stringify(r));return(0,p.jsxs)(`div`,{className:`med-feed-wide`,children:[(0,p.jsx)(Rk,{title:`Thống kê & báo cáo`,description:`Tương tác trên bảng tin nội bộ theo khoảng thời gian`,extra:(0,p.jsx)(Zk,{value:t,onChange:n})}),(0,p.jsxs)(`div`,{className:`med-feed-stack`,children:[(0,p.jsx)(cA,{overview:i.data,loading:i.loading}),(0,p.jsx)(xA,{range:r},JSON.stringify(r)),(0,p.jsx)(u.Card,{bordered:!1,className:`med-feed-report-panel med-feed-report-tabs`,children:(0,p.jsx)(u.Tabs,{items:[{key:`posts`,label:`Bài có tương tác cao`,children:(0,p.jsx)(hA,{range:r},JSON.stringify(r))},{key:`people`,label:`Người tương tác nhiều nhất`,children:(0,p.jsx)(_A,{range:r},JSON.stringify(r))}]})})]})]})}function CA(){let{me:e,basePath:t}=D(),n=t.replace(/\/+$/,``),r=[...e.canManage?[{to:n||`/`,label:`Duyệt bài viết`,icon:(0,p.jsx)(h.FileDoneOutlined,{}),end:!0}]:[],...e.canPost?[{to:`${n}/my-posts`,label:`Bài của tôi`,icon:(0,p.jsx)(h.ProfileOutlined,{})}]:[],...e.canManage?[{to:`${n}/reports`,label:`Thống kê & Báo cáo`,icon:(0,p.jsx)(h.BarChartOutlined,{})},{to:`${n}/events`,label:`Sự kiện`,icon:(0,p.jsx)(h.CalendarOutlined,{})},{to:`${n}/settings`,label:`Cấu hình`,icon:(0,p.jsx)(h.SettingOutlined,{})}]:[]];return r.length===0?(0,p.jsx)(`div`,{className:`med-feed-content`,children:(0,p.jsx)(u.Result,{status:`403`,title:`Bạn không có quyền quản lý bảng tin`})}):(0,p.jsxs)(`div`,{className:`med-feed-admin`,children:[(0,p.jsxs)(`aside`,{className:`med-feed-admin__sidebar`,children:[(0,p.jsxs)(`div`,{className:`med-feed-admin__brand`,children:[(0,p.jsx)(`span`,{className:`med-feed-admin__logo`,"aria-hidden":!0,children:`N`}),(0,p.jsxs)(`span`,{className:`med-feed-admin__brand-text`,children:[(0,p.jsx)(`strong`,{children:`Quản trị bảng tin`}),(0,p.jsx)(`span`,{children:`Bảng tin nội bộ`})]})]}),(0,p.jsx)(`div`,{className:`med-feed-admin__section`,children:`Điều hướng`}),(0,p.jsx)(`nav`,{className:`med-feed-admin__nav`,"aria-label":`Quản trị bảng tin`,children:r.map(e=>(0,p.jsxs)(m.NavLink,{to:e.to,end:e.end,className:({isActive:e})=>e?`med-feed-admin__nav-item med-feed-admin__nav-item--active`:`med-feed-admin__nav-item`,children:[(0,p.jsx)(`span`,{className:`med-feed-admin__nav-icon`,children:e.icon}),e.label]},e.to))})]}),(0,p.jsx)(`main`,{className:`med-feed-admin__main`,children:(0,p.jsxs)(m.Routes,{children:[(0,p.jsx)(m.Route,{index:!0,element:e.canManage?(0,p.jsx)(nA,{}):(0,p.jsx)(m.Navigate,{to:`${n}/my-posts`,replace:!0})}),(0,p.jsx)(m.Route,{path:`my-posts`,element:(0,p.jsx)(wA,{allowed:e.canPost,page:(0,p.jsx)(Bk,{})})}),(0,p.jsx)(m.Route,{path:`reports`,element:(0,p.jsx)(wA,{allowed:e.canManage,page:(0,p.jsx)(SA,{})})}),(0,p.jsx)(m.Route,{path:`events`,element:(0,p.jsx)(wA,{allowed:e.canManage,page:(0,p.jsx)(Uk,{})})}),(0,p.jsx)(m.Route,{path:`settings/*`,element:(0,p.jsx)(wA,{allowed:e.canManage,page:(0,p.jsx)(aA,{})})}),(0,p.jsx)(m.Route,{path:`posts/:postId`,element:(0,p.jsx)(Ah,{})}),(0,p.jsx)(m.Route,{path:`*`,element:(0,p.jsx)(u.Result,{status:`404`,title:`Không tìm thấy trang`})})]})})]})}function wA({allowed:e,page:t}){return e?(0,p.jsx)(p.Fragment,{children:t}):(0,p.jsx)(u.Result,{status:`403`,title:`Bạn không có quyền truy cập trang này`})}function TA(e){return(0,p.jsx)(Pe,{runtimeProps:{...e,isPostFeed:!0},isAdmin:!0,children:(0,p.jsx)(CA,{})})}exports.NewsfeedAdminModule=TA,exports.NewsfeedModule=Mh;
package/dist/index.js CHANGED
@@ -28608,7 +28608,7 @@ async function Pj(e, t) {
28608
28608
  try {
28609
28609
  if (await Nj(n, e)) return e;
28610
28610
  let r = new $A(), i = new xj({
28611
- format: new dj(),
28611
+ format: new dj({ fastStart: "in-memory" }),
28612
28612
  target: r
28613
28613
  }), a = await kj.init({
28614
28614
  input: n,
@@ -28616,11 +28616,15 @@ async function Pj(e, t) {
28616
28616
  video: { codec: "avc" },
28617
28617
  audio: { codec: "aac" }
28618
28618
  });
28619
- if (!a.isValid || (a.onProgress = t, await a.execute(), !r.buffer)) return e;
28619
+ if (!a.isValid) {
28620
+ let t = a.discardedTracks.map((e) => e.reason).join(", ");
28621
+ return console.warn(`Newsfeed: không convert được ${e.name} sang H.264 (${t})`), e;
28622
+ }
28623
+ if (a.onProgress = t, await a.execute(), !r.buffer) return e;
28620
28624
  let o = e.name.replace(/\.[^.]+$/, "") + ".mp4";
28621
28625
  return new File([r.buffer], o, { type: "video/mp4" });
28622
- } catch {
28623
- return e;
28626
+ } catch (t) {
28627
+ return console.warn(`Newsfeed: lỗi convert ${e.name} sang H.264`, t), e;
28624
28628
  } finally {
28625
28629
  n.dispose();
28626
28630
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@medipha/feed",
3
- "version": "0.2.9",
3
+ "version": "0.3.0",
4
4
  "description": "Embeddable Medic-ERP newsfeed module for React applications.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",