SPB Git

Repository Public

Media.tsx 13.4 KB 216 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/social-web/src/screens/Media.tsx9 * Module           : screens10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useRef, useState } from 'react';43import { api, get, post } from '../../../shared/api.ts';44import { usePrefs } from '../prefs.tsx';45import { useSession } from '../session.tsx';46import type { Media } from '../types.ts';47import { ActionStatus, Await, Check, CopyButton, Empty, Field, Hash, KV, Modal, Notice, PageHead, Panel, Tag, useAction, useLoad } from '../ui/core.tsx';4849const KINDS = ['announcement', 'release', 'statistic', 'app_capture'] as const;5051function StoredNote({ m }: { m: Media }) {52  const { t } = usePrefs();53  const stripped = Array.isArray(m.strippedMetadata) ? (m.strippedMetadata as unknown[]).map(String) : null;54  return (55    <div className="note note-info" role="status">56      <p><strong>{m.duplicate ? t('md.duplicate') : t('md.stored')}</strong> {m.width} × {m.height} px · <code>{m.mime}</code></p>57      <p>{t('c.hash')} <Hash value={m.sha256} full /></p>58      {m.duplicate ? null : stripped === null ? <p>{t('md.strippedUnknown')}</p> : stripped.length === 0 ? <p>{t('md.strippedNone')}</p> : <><p>{t('md.stripped')}</p><ul>{stripped.map((x) => <li key={x}><code>{x}</code></li>)}</ul></>}59      <p><Tag prefix="mediaStatus" value={m.status} /></p>60    </div>61  );62}6364export function MediaLibrary() {65  const { t, dt, num } = usePrefs();66  const s = useSession();67  const [brandId, setBrandId] = useState(s.brandId || (s.brands.length === 1 ? s.brands[0].id : ''));68  const effective = s.brandId || brandId;69  const list = useLoad(async () => (effective ? (await get<{ media: Media[] }>(`/v1/media?brandId=${effective}`)).media : null), [effective]);70  const [rights, setRights] = useState<Media | null>(null);71  const [reject, setReject] = useState<Media | null>(null);72  const brand = s.brandById(effective);73  return (74    <>75      <PageHead title={t('md.title')} lead={t('md.lead')}>{effective ? <button type="button" onClick={list.reload} disabled={list.loading}>{t('c.reload')}</button> : null}</PageHead>76      {!s.brandId ? <div className="filters"><Field label={t('c.brand')}><select value={brandId} onChange={(e) => setBrandId(e.target.value)}><option value="">{t('c.select')}</option>{s.brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</select></Field></div> : null}77      {!effective ? <Empty>{t('c.chooseBrand')}</Empty> : (<>78        <div className="grid-2">79          <Upload brandId={effective} onDone={list.reload} />80          <Template brandId={effective} onDone={list.reload} />81        </div>82        <Panel title={t('md.library')}>83          <p className="small">{t('md.urlNote')}</p>84          <Await of={list}>{(media) => !media || media.length === 0 ? <Empty>{t('md.empty')}</Empty> : (85            <ul className="media-grid">{media.map((m) => (86              <li key={m.id} className="card">87                {m.url ? <a href={m.url} target="_blank" rel="noopener noreferrer" className="media-thumb"><img src={m.url} alt={m.alt_text || t('md.noAlt', { name: m.original_name })} loading="lazy" /></a> : null}88                <div className="card-head"><h3 className="break">{m.original_name || '—'}</h3><Tag prefix="mediaStatus" value={m.status} /></div>89                <KV rows={[90                  [t('md.dimensions'), `${m.width} × ${m.height} px`],91                  [t('md.size'), `${num(Math.round(Number(m.bytes) / 1024))} ko · ${m.mime}`],92                  ['sha256', <><Hash value={m.sha256} /> <CopyButton text={m.sha256} /></>],93                  [t('md.added'), dt(m.created_at, brand?.timezone)],94                  [t('md.altText'), m.alt_text || '—'],95                  [t('md.rights'), m.rights && m.rights.owner ? <span>{m.rights.owner} — {m.rights.license} — {m.rights.source}{m.rights.attestedAt ? ` (${dt(m.rights.attestedAt, brand?.timezone)})` : ''}</span> : t('md.rightsNone')],96                ]} />97                <div className="row">98                  {m.status !== 'rejected' ? <button type="button" onClick={() => setRights(m)}>{m.status === 'approved' ? t('md.rightsEdit') : t('md.attest')}</button> : null}99                  {m.status !== 'rejected' ? <button type="button" onClick={() => setReject(m)}>{t('md.reject')}</button> : null}100                </div>101              </li>102            ))}</ul>103          )}</Await>104        </Panel>105      </>)}106      {rights ? <RightsDialog m={rights} onClose={() => setRights(null)} onDone={() => { setRights(null); list.reload(); }} /> : null}107      {reject ? <RejectDialog m={reject} onClose={() => setReject(null)} onDone={() => { setReject(null); list.reload(); }} /> : null}108    </>109  );110}111112function Upload({ brandId, onDone }: { brandId: string; onDone: () => void }) {113  const { t } = usePrefs();114  const input = useRef<HTMLInputElement>(null);115  const [file, setFile] = useState<File | null>(null);116  const [stored, setStored] = useState<Media | null>(null);117  const a = useAction();118  const send = async () => {119    if (!file) return;120    setStored(null);121    // Order matters: the server reads the fields that precede the file part.122    const fd = new FormData(); fd.append('brandId', brandId); fd.append('file', file, file.name);123    const r = await a.run(() => api<Media>('POST', '/v1/media', fd));124    if (r) { setStored(r); setFile(null); if (input.current) input.current.value = ''; onDone(); }125  };126  return (127    <Panel title={t('md.upload')}>128      <form className="form" onSubmit={(e) => { e.preventDefault(); void send(); }}>129        <Field label={t('md.file')} hint={t('md.fileHint')} wide><input ref={input} type="file" accept="image/jpeg,image/png,image/webp" onChange={(e) => setFile(e.target.files?.[0] ?? null)} required /></Field>130        <div className="row"><button type="submit" className="primary" disabled={!file || a.busy}>{t('md.send')}</button></div>131        <ActionStatus a={a} />132      </form>133      {stored ? <StoredNote m={stored} /> : null}134    </Panel>135  );136}137138function Template({ brandId, onDone }: { brandId: string; onDone: () => void }) {139  const { t } = usePrefs();140  const [f, setF] = useState({ kind: 'announcement' as (typeof KINDS)[number], headline: '', kicker: '', body: '', figure: '', figureLabel: '', source: '', version: '' });141  const [stored, setStored] = useState<Media | null>(null);142  const a = useAction();143  const opt = (v: string) => (v.trim() ? v.trim() : undefined);144  const send = async () => {145    setStored(null);146    const r = await a.run(() => post<Media>('/v1/media/template', { brandId, kind: f.kind, headline: f.headline.trim(), kicker: opt(f.kicker), body: opt(f.body), figure: opt(f.figure), figureLabel: opt(f.figureLabel), source: opt(f.source), version: opt(f.version) }));147    if (r) { setStored(r); onDone(); }148  };149  const stat = f.kind === 'statistic';150  return (151    <Panel title={t('md.template')}>152      <p className="small">{t('md.templateLead')}</p>153      <form className="form" onSubmit={(e) => { e.preventDefault(); void send(); }}>154        <div className="form-grid">155          <Field label={t('md.kind')}><select value={f.kind} onChange={(e) => setF({ ...f, kind: e.target.value as (typeof KINDS)[number] })}>{KINDS.map((k) => <option key={k} value={k}>{t(`md.kind.${k}`)}</option>)}</select></Field>156          <Field label={`${t('md.kicker')} (${t('c.optional')})`}><input value={f.kicker} onChange={(e) => setF({ ...f, kicker: e.target.value })} maxLength={40} /></Field>157          <Field label={t('md.headline')} wide><input value={f.headline} onChange={(e) => setF({ ...f, headline: e.target.value })} maxLength={160} required /></Field>158          <Field label={`${t('md.body')} (${t('c.optional')})`} wide><textarea value={f.body} onChange={(e) => setF({ ...f, body: e.target.value })} rows={2} maxLength={240} /></Field>159          {stat ? <>160            <Field label={t('md.figure')} hint={t('md.figureHint')}><input value={f.figure} onChange={(e) => setF({ ...f, figure: e.target.value })} maxLength={12} required /></Field>161            <Field label={`${t('md.figureLabel')} (${t('c.optional')})`}><input value={f.figureLabel} onChange={(e) => setF({ ...f, figureLabel: e.target.value })} maxLength={60} /></Field>162            <Field label={t('md.figureSource')} wide><input value={f.source} onChange={(e) => setF({ ...f, source: e.target.value })} maxLength={120} required /></Field>163          </> : null}164          {f.kind === 'release' ? <Field label={`${t('c.version')} (${t('c.optional')})`}><input value={f.version} onChange={(e) => setF({ ...f, version: e.target.value })} maxLength={20} className="mono" /></Field> : null}165        </div>166        <div className="row"><button type="submit" disabled={a.busy || !f.headline.trim()}>{t('md.generate')}</button></div>167        <ActionStatus a={a} />168      </form>169      {stored ? <StoredNote m={stored} /> : null}170    </Panel>171  );172}173174function RightsDialog({ m, onClose, onDone }: { m: Media; onClose: () => void; onDone: () => void }) {175  const { t } = usePrefs();176  const [f, setF] = useState({ owner: m.rights?.owner ?? '', license: m.rights?.license ?? '', source: m.rights?.source ?? '', altText: m.alt_text ?? '' });177  const [notListing, setNotListing] = useState(false);178  const [attest, setAttest] = useState(false);179  const a = useAction();180  const valid = f.owner.trim().length >= 2 && f.license.trim().length >= 2 && f.source.trim().length >= 2 && notListing && attest;181  const send = async () => { if (await a.run(() => post(`/v1/media/${m.id}/rights`, { owner: f.owner.trim(), license: f.license.trim(), source: f.source.trim(), thirdPartyListing: false, attest: true, ...(f.altText.trim() ? { altText: f.altText.trim() } : {}) }))) onDone(); };182  return (183    <Modal title={t('md.rights.title')} onClose={onClose}>184      <p>{t('md.rights.lead')}</p>185      {m.url ? <img className="dialog-img" src={m.url} alt={m.alt_text ?? m.original_name} /> : null}186      <form className="form" onSubmit={(e) => { e.preventDefault(); if (valid) void send(); }}>187        <Field label={t('md.rights.owner')} wide><input value={f.owner} onChange={(e) => setF({ ...f, owner: e.target.value })} maxLength={200} required /></Field>188        <Field label={t('md.rights.license')} wide><input value={f.license} onChange={(e) => setF({ ...f, license: e.target.value })} maxLength={300} required /></Field>189        <Field label={t('md.rights.source')} wide><input value={f.source} onChange={(e) => setF({ ...f, source: e.target.value })} maxLength={300} required /></Field>190        <Field label={`${t('md.altText')} (${t('c.optional')})`} wide><textarea value={f.altText} onChange={(e) => setF({ ...f, altText: e.target.value })} rows={2} maxLength={500} /></Field>191        <Check label={t('md.rights.notListing')} checked={notListing} onChange={setNotListing} />192        <Notice><p>{t('md.rights.listingRule')}</p></Notice>193        <Check label={t('md.rights.attest')} checked={attest} onChange={setAttest} />194        <div className="row"><button type="submit" className="primary" disabled={!valid || a.busy}>{t('md.attest')}</button><button type="button" onClick={onClose}>{t('c.cancel')}</button></div>195        <ActionStatus a={a} />196      </form>197    </Modal>198  );199}200function RejectDialog({ m, onClose, onDone }: { m: Media; onClose: () => void; onDone: () => void }) {201  const { t } = usePrefs();202  const [reason, setReason] = useState('');203  const a = useAction();204  const send = async () => { if (await a.run(() => post(`/v1/media/${m.id}/reject`, { reason: reason.trim() }))) onDone(); };205  return (206    <Modal title={t('md.reject.title')} onClose={onClose}>207      <p>{t('md.reject.lead')}</p>208      <form className="form" onSubmit={(e) => { e.preventDefault(); void send(); }}>209        <Field label={t('c.reason')} wide><textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={2} maxLength={300} required /></Field>210        <div className="row"><button type="submit" className="danger" disabled={reason.trim().length < 3 || a.busy}>{t('md.reject')}</button><button type="button" onClick={onClose}>{t('c.cancel')}</button></div>211        <ActionStatus a={a} />212      </form>213    </Modal>214  );215}216
Files main
Menu

Theme