import { randomUUID } from "node:crypto"; import { escapeHtml as esc } from "./html.mjs"; import { communicationAssets, layoutWorkbench } from "./layout-workbench.mjs"; import { embeddedLayout, previewTheme } from "./shell.mjs"; const people = { mara: ["Mara Lind", "ML", "clay"], julian: ["Julian Park", "JP", "moss"], iris: ["Iris Chen", "IC", "sky"], sofia: ["Sofia Bell", "SB", "rose"], theo: ["Theo Sato", "TS", "sand"], you: ["You", "YO", "neutral"], }; const mail = [ { id:"proofs", person:"mara", subject:"The Field Notes proofs are in", time:"09:41", date:"Today", preview:"We’ve got the first set back from the printer.", body:["Hi team,", "We’ve got the first set back from the printer. The warm grey stock gives the cover photograph a softer edge. I’d keep it uncoated.", "Can we lock the paper choice before Thursday’s press check?", "Mara"], tag:"Field Notes" }, { id:"materials", person:"julian", subject:"Material library update", time:"08:26", date:"Today", preview:"Two new finishes for the Arc collection.", body:["Morning,", "Two new finishes for the Arc collection arrived today. I’ve set aside a sample of each on the studio table.", "Drop by when you have a moment. I’d love a second pair of eyes on the brushed finish."], tag:"Materials" }, { id:"bookings", person:"iris", subject:"November studio bookings", time:"Tue", date:"Tuesday", preview:"Here’s the revised plan for shoot week.", body:["Hi everyone,", "Here’s the revised plan for shoot week. Tuesday is reserved for product stills and Wednesday for the oak series.", "The studio is free again on Thursday afternoon."], tag:"Operations" }, { id:"packing", person:"sofia", subject:"A note on the new packaging", time:"Mon", date:"Monday", preview:"The test cartons held up on their first trip.", body:["A quick update from dispatch. The test cartons held up on their first trip. All twelve pieces arrived in good order.", "I’ll bring the packing samples to our next review."], tag:"Dispatch" }, { id:"samples", person:"theo", subject:"Archive shelf inventory", time:"Fri", date:"Friday", preview:"The sample shelf is ready for the handover.", body:["The sample shelf is ready for the handover. I’ve counted each finish and put a reference card in every tray.", "Thanks for helping with the labels."], tag:"Archive" }, ]; const channels = [ { id:"studio-floor", name:"studio-floor", description:"Daily work from the studio", members:["mara","julian","iris"], messages:[ ["mara","09:32","The Field Notes proofs are on the big table. Here’s the cover photograph for reference."], ["julian","09:35","I put the oak and graphite samples beside them, so we can check all three together."], ["iris","09:41","I’ll take a look before the press check. Thanks for laying those out!"], ] }, { id:"design-review", name:"design-review", description:"Materials, finishes and open design questions", members:["iris","theo","mara"], messages:[ ["iris","10:12","The brushed finish is catching the light better than yesterday’s sample."], ["theo","10:18","Agreed. I’ll add it to the review tray with the original so we have a direct comparison."], ] }, { id:"dispatch", name:"dispatch", description:"Shipping, packing and delivery updates", members:["sofia","julian"], messages:[ ["sofia","08:15","All twelve pieces arrived safely. The new inserts did their job."], ["julian","08:22","That’s good to hear. Let’s use the same packing for the next run."], ] }, ]; const directs = [ { id:"mara", name:"Mara Lind", description:"Direct conversation", members:["mara"], messages:[["mara","09:14","Could you bring the paper swatches to Thursday’s press check?"]] }, { id:"theo", name:"Theo Sato", description:"Direct conversation", members:["theo"], messages:[["theo","08:52","The reference cards are ready. I left them on your desk."]] }, ]; const rooms = [...channels,...directs]; const paths = { mail:'', chat:'', archive:'', inbox:'', download:'', back:'', send:'', reply:'', hash:'', }; function icon(key) { return ``; } function avatar(person, small = false) { const [,initials,color] = people[person]; return ``; } function appUrl(screen, params = {}, fragment = false) { const query = new URLSearchParams(Object.entries(params).filter(([,v])=>v)); return (fragment ? "/demo/layouts/" : "/layouts/") + screen + (query.size ? "?" + query : ""); } function navigate(screen, params) { const url=esc(appUrl(screen,params)); return `href="${url}" hx-get="${esc(appUrl(screen,params,true))}" hx-push-url="${url}"`; } function formAction(screen, action) { const url = `/demo/layouts/${screen}/${action}`; return `method="post" action="${url}" hx-post="${url}"`; } function hidden(name,value) { return ``; } function feedback(error) { return ``; } function coverAttachment() { return ` Cover photographWebP · 13 KB${icon("download")}`; } function formState(options) { return { notice:"", focus:"", error:"", draft:"", ...options }; } function draftMarker(id) { return ` `; } function frame(screen, title, address, detail, content, options, draftScope) { return `
${icon(screen)}

${title}

${address}
${content}${options.notice ? `

${esc(options.notice)}

` : ""}
`; } function mailScreen(state, params, options = {}) { const result=formState(options); const folder=params.get("folder")==="archive"?"archive":"inbox"; const available=mail.filter(item => state.archived.has(item.id)===(folder==="archive")); const selected=available.find(item=>item.id===params.get("thread")) || available[0]; if(selected && params.get("thread")===selected.id) state.read.add(selected.id); const rows=available.map(item=>` ${avatar(item.person,true)}${people[item.person][0]}${item.time} ${draftMarker(item.id)}${state.read.has(item.id)?"":'Unread: '}${item.subject}${esc(state.replies.get(item.id)?.at(-1)?.text || item.preview)}`).join(""); const folders=[["inbox","Inbox",mail.length-state.archived.size],["archive","Archive",state.archived.size]]; const sidebar=``; const divider = ``; let reader='

Select a message to read it.

'; if(selected) { const { id,person,tag,subject,date,time,body }=selected; const [name]=people[person]; const label=folder==="archive"?"Move to inbox":"Archive"; const replies=(state.replies.get(id)||[]).map(reply=>`
${avatar("you",true)}You

${esc(reply.text)}

`).join(""); reader=`
${icon("back")} Messages${tag}
${hidden("thread",id)}${hidden("folder",folder)}${hidden("destination",folder==="archive"?"inbox":"archive")} ${feedback("")}

${subject}

${body.map(line=>`

${line}

`).join("")}
${id==="proofs" ? coverAttachment() : ""}${replies}
${hidden("thread",id)}${hidden("folder",folder)}${hidden("nonce", randomUUID())}
${feedback(result.error)}
`; } return frame("mail","Studio mail","studio@north.example",Boolean(selected && params.has("thread")), `
${sidebar}${divider}${reader}
`,result,state.draftScope); } function chatScreen(state, params, options={}) { const result=formState(options); const room=rooms.find(item=>item.id===params.get("room"))||rooms[0]; const direct=directs.includes(room); function roomLink(entry, dm=false) { return `${dm?avatar(entry.id,true):icon("hash")}${entry.name}${draftMarker(entry.id)}`; } const sidebar=``; const messages=[...room.messages,...(state.chat.get(room.id)||[]).map(reply=>["you",reply.time,reply.text])]; const feed=messages.map(([person,time,text],index)=>`
  • ${avatar(person,true)}

    ${people[person][0]}

    ${esc(text)}

    ${room.id==="studio-floor" && index===0 ? coverAttachment() : ""}
  • `).join(""); const label=direct ? room.name : "#"+room.name; const main=`
    ${icon("back")} Conversations

    ${direct?"":icon("hash")}${room.name}

    ${room.description}

    ${room.members.map(p=>avatar(p,true)).join("")}
    Today
      ${feed}
    ${hidden("room",room.id)}${hidden("nonce",randomUUID())}
    ${feedback(result.error)}
    `; return frame("chat","Team chat","North Studio",params.get("view")!=="channels",`
    ${sidebar}${main}
    `,result,state.draftScope); } function newSession() { return { draftScope:randomUUID(), archived:new Set(["samples"]), read:new Set(["proofs","packing","samples"]), replies:new Map(), chat:new Map() }; } async function readBody(request) { let size=0; const chunks=[]; for await (const chunk of request) { size+=chunk.length; if(size>24000) return null; chunks.push(chunk); } return new URLSearchParams(Buffer.concat(chunks).toString("utf8")); } export function createCommunicationLayouts() { const sessions=new Map(); function getSession(request,response) { let key=request.headers.cookie?.match(/(?:^|;\s*)relay_comm=([a-f\d-]{36})(?:;|$)/)?.[1]; let state=sessions.get(key); if(!state) { key=randomUUID(); state=newSession(); response.appendHeader("Set-Cookie",`relay_comm=${key}; Path=/; HttpOnly; SameSite=Lax`); } sessions.delete(key); sessions.set(key,state); if(sessions.size>256) sessions.delete(sessions.keys().next().value); return state; } function draw(screen,state,params,options) { return screen==="mail" ? mailScreen(state,params,options) : chatScreen(state,params,options); } return { render(screen,request,response,params) { return draw(screen,getSession(request,response),params); }, async handle(request,response,url) { const match=url.pathname.match(/^\/demo\/layouts\/(mail|chat)(?:\/(move|reply|send))?$/); if(!match) return false; const [,screen,action]=match; const headers={"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}; function send(html,status=200,extra={}) { response.writeHead(status,{...headers,...extra});response.end(html);return true; } if(!action && request.method==="GET") { const state=getSession(request,response); return send(draw(screen,state,url.searchParams,{focus:url.searchParams.has("thread")||url.searchParams.has("room")?"heading":"list"})); } if(request.method!=="POST" || !action) return send("Method not allowed.",405,{Allow:action?"POST":"GET"}); const params=await readBody(request); if(!params) return send("Message is too large.",413); const standalone = !request.headers["hx-request"] && url.searchParams.get("embed") === "1"; const theme = previewTheme(url.searchParams.get("theme")); const state=getSession(request,response); const room=screen==="mail"?mail.find(m=>m.id===params.get("thread")):rooms.find(r=>r.id===params.get("room")); if(!room || (screen==="mail" ? action==="send":action!=="send")) return send("Conversation not found.",404); let next=screen==="mail"?{folder:state.archived.has(room.id)?"archive":"inbox",thread:room.id}:{room:room.id}; let notice, focus="composer"; if(action==="move") { const archive=params.get("destination")==="archive"; if(!archive && params.get("destination")!=="inbox") return send("Unknown destination.",400); if(archive) state.archived.add(room.id); else state.archived.delete(room.id); next={folder:archive?"inbox":"archive"}; notice=archive?"Message archived.":"Message moved to inbox."; focus="list"; } else { const text=params.get("message")||""; const notes=screen==="chat"?state.chat:state.replies; const entries=notes.get(room.id)||[]; const nonce=params.get("nonce")?.slice(0,64); const previous=nonce && entries.find(item=>item.nonce===nonce); let error; if(!text.trim() || text.length>1600) error="Enter a message between 1 and 1,600 characters."; else if(previous && previous.text!==text.trim()) error="The earlier message was sent. Review your changes before sending again."; if(error) { const content=draw(screen,state,new URLSearchParams(next),{error,draft:text,focus}); if(request.headers["hx-request"]) return send(content,422); const assets = communicationAssets(screen); if(standalone) return send(embeddedLayout({ title: "Check your message", content, assets, mode: theme }), 422); return send(layoutWorkbench({ screen, title: "Check your message", content, assets, params: next, indexable: false }), 422); } if(!previous) { entries.push({text:text.trim(),time:new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit"}).format(new Date()),nonce}); notes.set(room.id,entries.slice(-50)); } notice=screen==="chat"?"Message sent.":"Reply sent."; } const location=appUrl(screen,standalone ? { ...next, embed: "1", theme } : next); if(!request.headers["hx-request"]) return send("",303,{Location:location}); return send(draw(screen,state,new URLSearchParams(next),{notice,focus}),200,{"HX-Replace-Url":location}); }, }; }