@svgrid/enterprise 3.1.58 → 3.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/svgrid-enterprise.svelte-external.js +1 -1
- package/dist/designer/assets/{index-DoEhPIfX.js → index-BC3lgv-R.js} +1 -1
- package/dist/designer/index.html +1 -1
- package/dist/fields/FieldEditor.svelte +30 -6
- package/dist/fields/PeopleRulePicker.svelte +34 -0
- package/dist/fields/PeopleRulePicker.svelte.d.ts +16 -0
- package/dist/fields/PropertyInput.svelte +12 -1
- package/dist/fields/RecordView.svelte +26 -8
- package/dist/fields/SelectEditor.svelte +1 -1
- package/dist/fields/activity.svelte.d.ts +34 -0
- package/dist/fields/activity.svelte.js +1 -1
- package/dist/fields/base-permissions.d.ts +13 -0
- package/dist/fields/base-permissions.js +1 -1
- package/dist/fields/base-sync.js +1 -1
- package/dist/fields/builtin-types.js +1 -1
- package/dist/fields/button-host.d.ts +2 -0
- package/dist/fields/button-host.js +1 -1
- package/dist/fields/field-access.svelte.d.ts +38 -8
- package/dist/fields/field-access.svelte.js +1 -1
- package/dist/fields/index.d.ts +4 -3
- package/dist/fields/index.js +1 -1
- package/dist/fields/messages/fields.d.ts +21 -0
- package/dist/fields/messages/fields.js +1 -1
- package/dist/fields/messages/record.d.ts +7 -0
- package/dist/fields/messages/record.js +1 -1
- package/dist/fields/messages.svelte.d.ts +28 -0
- package/dist/fields/people-rule.d.ts +35 -0
- package/dist/fields/people-rule.js +1 -0
- package/dist/fields/record-delete.svelte.js +1 -1
- package/dist/fields/record-menu.js +1 -1
- package/dist/fields/registry.svelte.d.ts +11 -0
- package/dist/fields/registry.svelte.js +1 -1
- package/dist/fields/view-model.js +1 -1
- package/dist/node/studio.js +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/dist/wc/sv-base-element.js +97 -97
- package/package.json +3 -3
|
@@ -1525,7 +1525,7 @@ ${O}
|
|
|
1525
1525
|
@keyframes st-home-spin { to { transform: rotate(360deg); } }
|
|
1526
1526
|
</style>
|
|
1527
1527
|
`}}function $S(t){for(let a of t)ls(a);let r=new Map(t.map(a=>[a.name,a])),n=t.map(a=>{let l=xse(a,r);return{schema:kse(a,l),infos:l}});return{entries:n,seed:_se(n)}}function ED(t,r={}){let{entries:n,seed:a}=$S(t),{file:l,needs:i}=Vse(n,a,r.sources,r.supabaseConn,r.serverMemory),o=[Cse(n),l];(i.supabase||r.supabaseAuth)&&!i.supabaseUrl&&(r.supabaseConn?.url||r.supabaseConn?.key)&&(i.supabaseUrl=r.supabaseConn.url,i.supabaseKey=r.supabaseConn.key),(i.supabase||r.supabaseAuth)&&o.push(Hse(i));for(let s of i.sqlRoutes)o.push(Fse(s.schema,s.table,s.dialect,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],dbSchema:s.dbSchema,tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}));if(i.memoryRoutes.length){o.push(Lse(i.memoryRoutes));for(let s of i.memoryRoutes)o.push(Ose(s.schema,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}))}return{files:o,prepared:n.map(s=>s.schema)}}function Kse(t){if(t.length===0)throw Error("emitStudioApp: no schemas to emit");let{files:r,prepared:n}=ED(t),a=n.map(i=>{let o=za(i);return{href:`/${o.route}`,label:o.label}}),l={path:"src/custom.css",description:"Your custom styles (imported after app.css so it overrides).",userOwned:!0,contents:`/* Your custom styles. Imported after app.css, so these rules override the defaults. */
|
|
1528
|
-
`};return[...r,...n.map(i=>Wse(i)),AD(a),MD(a),l]}var Gse="3.1.
|
|
1528
|
+
`};return[...r,...n.map(i=>Wse(i)),AD(a),MD(a),l]}var Gse="3.1.60",Yse="3.0.38",ul=(t,r)=>t.some(n=>n.config.kind===r),RD=t=>`activeTab_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,Zm=(t,r)=>`${t}-${r}`,ID=t=>`accOpen_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,Qm=(t,r)=>`${t}-s${r}`,ev=t=>`md_${t.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function Xse(t){switch(t.type){case"number":{let r=t.decimals;return r==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${r}, maximumFractionDigits: ${r} } }`}case"currency":return`{ type: 'currency', currency: ${Zr(t.currency||"USD")} }`;case"percent":{let r=["type: 'percent'"];return t.valueIsPercentPoints&&r.push("valueIsPercentPoints: true"),t.decimals!=null&&r.push(`options: { minimumFractionDigits: ${t.decimals}, maximumFractionDigits: ${t.decimals} }`),`{ ${r.join(", ")} }`}case"date":case"datetime":return t.pattern?`{ type: '${t.type}', pattern: ${Zr(t.pattern)} }`:`{ type: '${t.type}' }`}}function Jse(t,r,n,a){if(r.config.kind!=="grid")return`schemaToColumns(${t})`;let l=r.config,i=r.id.replace(/-/g,"_"),o=l.columns.filter(b=>b.show),s=new Set(o.map(b=>b.field)),c=new Set,d=o.map(b=>{let w=a?.get(b.field);return{c:b,col:w&&!s.has(w)?w:b.field}}).filter(b=>!c.has(b.col)&&!!c.add(b.col)),u=l.editing==="inline"?"":", editable: false";if(d.length===0)return u?`schemaToColumns(${t}).map((c) => ({ ...c${u} }))`:`schemaToColumns(${t})`;let p=d.map(b=>`'${b.col}'`),f=d.map(({c:b,col:w})=>{let v=[];return b.header&&v.push(`header: ${JSON.stringify(b.header)}`),b.width!=null&&v.push(`width: ${b.width}`),b.align&&v.push(`align: '${b.align}'`),b.aggregate&&v.push(`aggregate: '${b.aggregate}'`),l.treeData&&b.field===l.treeData.labelField&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(treeCell_${i}, { value: ctx.getValue(), row: ctx.row.original })`):b.cellType&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(${zD(i,b.field)}, { value: ctx.getValue() })`):b.format&&v.push(`format: ${Xse(b.format)}`),v.length?`'${w}': { ${v.join(", ")} }`:null}).filter(b=>!!b),y=f.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${f.join(", ")} };`:"",h=f.length?", ...(ov[String(c.field)] ?? {})":"",_=`[${p.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${t});${y} return ${u||h?`${_}.map((c) => ({ ...c${u}${h} }))`:_} })()`}function ec(t,r){let n=[`grid-column: span ${Xie(t)}`,"min-width: 0"];r&&n.push(r);let a=Zie(t.style);return a&&n.push(a),`style="${n.join("; ")}"`}var Zse=t=>t&&t.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Iu(t,r){let n=[r,Yie(t)].filter(Boolean).join(" ");return n?` class="${n}"`:""}function n1(t){let r=cS(t.className);return r?` ${r}`:""}function Qse(t){let r=Af(t);if(r==="grid"){let n=goe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${n.rowGap}px ${n.colGap}px; align-items: ${n.align};${a} }
|
|
1529
1529
|
@media (max-width: ${n.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
|
|
1530
1530
|
`}if(r==="stack"){let n=foe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px;${n.align==="center"?" margin-inline: auto;":""}`:"",l=n.minHeight?`
|
|
1531
1531
|
.st-stack > * { min-height: ${n.minHeight}px; }`:"",i=n.dividers?`
|
|
@@ -76332,7 +76332,7 @@ ${st}
|
|
|
76332
76332
|
.st-home a { color: var(--sg-accent, #6366f1); font-weight: 600; }
|
|
76333
76333
|
@keyframes st-home-spin { to { transform: rotate(360deg); } }
|
|
76334
76334
|
</style>
|
|
76335
|
-
`}}function s2e(a){for(let p of a)G4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=kpr(p,i);return{schema:Ppr(p,f),infos:f}});return{entries:l,seed:Cpr(l)}}function rur(a,i={}){let{entries:l,seed:p}=s2e(a),{file:f,needs:g}=Ypr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[Opr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Zpr(g));for(let S of g.sqlRoutes)_.push(Upr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Hpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(Vpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var nur="3.1.
|
|
76335
|
+
`}}function s2e(a){for(let p of a)G4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=kpr(p,i);return{schema:Ppr(p,f),infos:f}});return{entries:l,seed:Cpr(l)}}function rur(a,i={}){let{entries:l,seed:p}=s2e(a),{file:f,needs:g}=Ypr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[Opr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Zpr(g));for(let S of g.sqlRoutes)_.push(Upr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Hpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(Vpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var nur="3.1.60",our="3.0.38",sb=(a,i)=>a.some(l=>l.config.kind===i),qit=a=>`activeTab_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,XZ=(a,i)=>`${a}-${i}`,Kit=a=>`accOpen_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,JZ=(a,i)=>`${a}-s${i}`,YZ=a=>`md_${a.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function aur(a){switch(a.type){case"number":{let i=a.decimals;return i==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${i}, maximumFractionDigits: ${i} } }`}case"currency":return`{ type: 'currency', currency: ${cu(a.currency||"USD")} }`;case"percent":{let i=["type: 'percent'"];return a.valueIsPercentPoints&&i.push("valueIsPercentPoints: true"),a.decimals!=null&&i.push(`options: { minimumFractionDigits: ${a.decimals}, maximumFractionDigits: ${a.decimals} }`),`{ ${i.join(", ")} }`}case"date":case"datetime":return a.pattern?`{ type: '${a.type}', pattern: ${cu(a.pattern)} }`:`{ type: '${a.type}' }`}}function iur(a,i,l,p){if(i.config.kind!=="grid")return`schemaToColumns(${a})`;let f=i.config,g=i.id.replace(/-/g,"_"),_=f.columns.filter(be=>be.show),S=new Set(_.map(be=>be.field)),A=new Set,k=_.map(be=>{let Be=p?.get(be.field);return{c:be,col:Be&&!S.has(Be)?Be:be.field}}).filter(be=>!A.has(be.col)&&!!A.add(be.col)),L=f.editing==="inline"?"":", editable: false";if(k.length===0)return L?`schemaToColumns(${a}).map((c) => ({ ...c${L} }))`:`schemaToColumns(${a})`;let F=k.map(be=>`'${be.col}'`),ee=k.map(({c:be,col:Be})=>{let Ue=[];return be.header&&Ue.push(`header: ${JSON.stringify(be.header)}`),be.width!=null&&Ue.push(`width: ${be.width}`),be.align&&Ue.push(`align: '${be.align}'`),be.aggregate&&Ue.push(`aggregate: '${be.aggregate}'`),f.treeData&&be.field===f.treeData.labelField&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(treeCell_${g}, { value: ctx.getValue(), row: ctx.row.original })`):be.cellType&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(${est(g,be.field)}, { value: ctx.getValue() })`):be.format&&Ue.push(`format: ${aur(be.format)}`),Ue.length?`'${Be}': { ${Ue.join(", ")} }`:null}).filter(be=>!!be),J=ee.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${ee.join(", ")} };`:"",te=ee.length?", ...(ov[String(c.field)] ?? {})":"",Ie=`[${F.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${a});${J} return ${L||te?`${Ie}.map((c) => ({ ...c${L}${te} }))`:Ie} })()`}function eW(a,i){let l=[`grid-column: span ${yM(a)}`,"min-width: 0"];i&&l.push(i);let p=vit(a.style);return p&&l.push(p),`style="${l.join("; ")}"`}var sur=a=>a&&a.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function z8(a,i){let l=[i,LH(a)].filter(Boolean).join(" ");return l?` class="${l}"`:""}function ofe(a){let i=WZ(a.className);return i?` ${i}`:""}function lur(a){let i=iR(a);if(i==="grid"){let l=qDe(a),p=l.maxWidth?` max-width: ${l.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${l.rowGap}px ${l.colGap}px; align-items: ${l.align};${p} }
|
|
76336
76336
|
@media (max-width: ${l.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
|
|
76337
76337
|
`}if(i==="stack"){let l=que(a),p=l.maxWidth?` max-width: ${l.maxWidth}px;${l.align==="center"?" margin-inline: auto;":""}`:"",f=l.minHeight?`
|
|
76338
76338
|
.st-stack > * { min-height: ${l.minHeight}px; }`:"",g=l.dividers?`
|
package/dist/designer/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>SvGrid Studio - Designer</title>
|
|
7
|
-
<script type="module" crossorigin src="./assets/index-
|
|
7
|
+
<script type="module" crossorigin src="./assets/index-BC3lgv-R.js"></script>
|
|
8
8
|
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-Dd_uD5pT.js">
|
|
9
9
|
<link rel="modulepreload" crossorigin href="./assets/index-client-CwjHmKgT.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="./assets/disclose-version-xihTtKlq.js">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{tick}from"svelte";import{SvModal}from"@svgrid/grid";import PropertyInput from"./PropertyInput.svelte";import{listFieldTypes,getFieldType,originalColumn}from"./registry.svelte";import{addField,defId,nameTaken,optionRecords,plainDef,previewChange,previewOptions,updateField}from"./field-ops";import{feedRequest}from"./view-feed.svelte";import{withOptionIds}from"./select-options";import{columnResolver,formulaError}from"./formula";import{aiPromptError}from"./ai-prompt";import{canProtectFields,fieldEditors}from"./field-access.svelte";import{getCurrentUser,getFieldUsers}from"./sources.svelte";import UserFace from"./UserFace.svelte";import{bm,bmCount}from"./messages.svelte";let{ctrl,mode,columnId,index="end",preset,onClose}=$props();const existing=mode==="edit"&&columnId?ctrl.internalColumns.find(d=>defId(d)===columnId):null;const plain=existing?plainDef(existing):null;const recordKey=plain?.recordKey===true;const allowed=$derived.by(()=>{const cfg=ctrl.props.columnAdder;const ids=cfg&&typeof cfg==="object"&&Array.isArray(cfg.types)?cfg.types:null;const types=listFieldTypes();return ids?ids.map(id=>types.find(t=>t.id===id)).filter(t=>!!t):types.filter(t=>!t.editAs)});const alias=getFieldType(plain?.fieldType)?.editAs;const start=mode==="add"&&preset?preset:null;let name=$state(String(start?.name??plain?.header??""));let fieldType=$state(start?.fieldType??alias?.type??String(plain?.fieldType??"text"));let props=$state(start?{...getFieldType(start.fieldType)?.defaults??{},...start.fieldProps??{}}:{...plain?.fieldProps??{},...alias?.props??{}});if(Array.isArray(props.options))props.options=withOptionIds(props.options);let description=$state(String(plain?.description??""));let search=$state("");let pickerOpen=$state(mode==="add"&&!start);let open=$state(true);const type=$derived(getFieldType(fieldType));const shownTypes=$derived(allowed.filter(t=>!search||t.label.toLowerCase().includes(search.toLowerCase())));const fallbackName=$derived.by(()=>{const base=type?.label??bm("fields.fallbackName");let n=base;for(let i=2;nameTaken(ctrl,n,columnId);i++)n=`${base} ${i}`;return n});const finalName=$derived(name.trim()||(mode==="add"?fallbackName:""));const nameError=$derived(!finalName?bm("fields.nameRequired"):nameTaken(ctrl,finalName,columnId)?bm("fields.nameTaken"):null);const cleared=$derived(mode==="edit"&&columnId?previewChange(ctrl,columnId,{name,fieldType,fieldProps:props}):0);const fromType=plain?.fieldType?String(plain.fieldType):void 0;const warn=$derived(mode==="edit"&&!!fromType&&fromType!==fieldType&&(fieldType!==alias?.type||cleared>0));const optionChange=$derived(mode==="edit"&&columnId?previewOptions(ctrl,columnId,{name,fieldType,fieldProps:props}):null);const touchedNames=$derived(optionChange?[...optionChange.removed,...optionChange.renamed.keys()]:[]);let serverUse=$state.raw(null);const asksServer=!!(ctrl.props.rowModel||ctrl.props.baseFeed);$effect(()=>{const names=touchedNames;const source=ctrl.props.baseSource;if(!asksServer||!source||!names.length||!columnId)return;let gone=false;const multi=fieldType==="multiSelect";const holding=value=>({kind:"fieldFilter",conjunction:"and",conditions:[{column:columnId,kind:multi?"multi":"select",op:multi?"hasAnyOf":"isAnyOf",value:[value]}]});void Promise.all(names.map(n=>source.getRows(feedRequest({expression:holding(n)},{})).then(r=>[n,r.rowCount]))).then(list=>{if(!gone)serverUse=new Map(list)},()=>{});return()=>{gone=true}});const useOfOptions=$derived(asksServer?serverUse:columnId&&touchedNames.length?optionRecords(ctrl,columnId,touchedNames):null);const optionNotes=$derived.by(()=>{const c=optionChange;const use=useOfOptions;if(!c||!use)return[];const notes=[];for(const name2 of c.removed)if(use.get(name2))notes.push(bmCount("fields.optionRemoved",use.get(name2),{name:name2}));if(asksServer){for(const name2 of c.renamed.keys())if(use.get(name2))notes.push(bmCount("fields.optionRenamed",use.get(name2),{name:name2}))}return notes});const optionProblem=$derived.by(()=>{const list=props.options??[];const seen=new Set;for(const o of list){const v=String(o.value??"").trim();if(v&&seen.has(v))return bm("fields.optionsSameName",{name:v});if(v)seen.add(v)}const was=withOptionIds(plain?.fieldProps?.options);const blank=list.find(o=>!String(o.value??"").trim()&&was.some(w=>w.id===o.id));return blank?bm("fields.optionNeedsName",{name:was.find(w=>w.id===blank.id).value}):null});const inputValue=e=>e.currentTarget.value;let searchBox=$state(null);function openPicker(){pickerOpen=true;void tick().then(()=>searchBox?.focus())}function typeSearchKey(e){if(e.key!=="Enter"||e.isComposing)return;e.preventDefault();const first=grouped[0]?.types[0];if(first)pickType(first.id)}function pickType(id){if(id===fieldType)return;fieldType=id;pickerOpen=false;search="";const next=getFieldType(id);const keep={...next?.defaults??{}};for(const p of next?.properties??[])if(props[p.key]!==void 0)keep[p.key]=props[p.key];if(props.editors!==void 0)keep.editors=props.editors;props=keep}const editorCtx=$derived({ctrl,props:{...type?.defaults??{},...props},columns:ctrl.internalColumns.map(c=>originalColumn(c)).filter(c=>defId(c)!==columnId),self:[plain?.field,columnId,plain?.header,finalName]});const shownProps=$derived((type?.properties??[]).filter(p=>!p.visible||p.visible(editorCtx.props)));const formulaProblem=$derived.by(()=>{for(const p of shownProps){if(p.kind!=="formula"&&p.kind!=="prompt")continue;const src=String(editorCtx.props[p.key]??"");const message=!src.trim()?null:p.kind==="prompt"?aiPromptError(src,editorCtx.columns,editorCtx.self):formulaError(src,columnResolver(editorCtx.columns,editorCtx.self));if(message)return bm(p.kind==="prompt"?"fields.fixPromptFirst":"fields.fixFormulaFirst",{message})}return null});const NEEDS={lookup:["linkField","field"],rollup:["linkField","field"],count:["linkField"],ai:["prompt"]};const missing=$derived((NEEDS[fieldType]??[]).find(key=>!String(editorCtx.props[key]??"").trim())??null);const missingText=$derived.by(()=>{if(missing==="prompt")return bm("fields.needPrompt");if(missing==="field")return bm("fields.needLinkedField");return editorCtx.columns.some(c=>c.fieldType==="link")?bm("fields.needLinkField"):bm("fields.needLinkFieldFirst")});let tried=$state(false);const GROUPS=[{id:"basic",key:"fields.groupBasic"},{id:"number",key:"fields.groupNumber"},{id:"date",key:"fields.groupDate"},{id:"people",key:"fields.groupPeople"},{id:"computed",key:"fields.groupComputed"},{id:"relation",key:"fields.groupRelation"}];const groupOf=t=>GROUPS.some(g=>g.id===t.group)?t.group:"basic";const grouped=$derived(GROUPS.map(g=>({...g,types:shownTypes.filter(t=>groupOf(t)===g.id)})).filter(g=>g.types.length));const takesEdits=$derived.by(()=>{try{return type?.fill?.({id:"_",field:"_",fieldType},{...type.defaults??{}},{columns:[]})?.editable!==false}catch{return true}});const editors=$derived(fieldEditors(props));const me=$derived(getCurrentUser());const people=$derived.by(()=>{const list=[...getFieldUsers()];if(me&&!list.some(u=>u.id===me.id))list.unshift(me);for(const id of editors??[])if(!list.some(u=>u.id===id))list.push({id,name:id});return list});function restrict(on){const{editors:_drop,...rest}=props;props=on?{...rest,editors:me?[me.id]:[]}:rest}function toggleEditor(id){const list=editors??[];props={...props,editors:list.includes(id)?list.filter(x=>x!==id):[...list,id]}}function save(){if(nameError||formulaProblem||optionProblem)return;if(missing){const key=missing;tried=true;void tick().then(()=>document.getElementById(`sv-fed-${key}`)?.focus());return}const draft={name:finalName,fieldType,fieldProps:$state.snapshot(props),description};if(mode==="edit"&&columnId)updateField(ctrl,columnId,draft);else addField(ctrl,draft,index);close()}function close(){open=false;onClose()}
|
|
2
|
+
import{tick}from"svelte";import{SvModal}from"@svgrid/grid";import PropertyInput from"./PropertyInput.svelte";import{listFieldTypes,getFieldType,originalColumn}from"./registry.svelte";import{addField,defId,nameTaken,optionRecords,plainDef,previewChange,previewOptions,updateField}from"./field-ops";import{feedRequest}from"./view-feed.svelte";import{withOptionIds}from"./select-options";import{columnResolver,formulaError}from"./formula";import{aiPromptError}from"./ai-prompt";import{canProtectFields,fieldEditors}from"./field-access.svelte";import{fieldToken,isFieldToken,ruleFields}from"./people-rule";import{getCurrentUser,getFieldUsers}from"./sources.svelte";import UserFace from"./UserFace.svelte";import{bm,bmCount}from"./messages.svelte";let{ctrl,mode,columnId,index="end",preset,onClose}=$props();const existing=mode==="edit"&&columnId?ctrl.internalColumns.find(d=>defId(d)===columnId):null;const plain=existing?plainDef(existing):null;const recordKey=plain?.recordKey===true;const allowed=$derived.by(()=>{const cfg=ctrl.props.columnAdder;const ids=cfg&&typeof cfg==="object"&&Array.isArray(cfg.types)?cfg.types:null;const types=listFieldTypes();return ids?ids.map(id=>types.find(t=>t.id===id)).filter(t=>!!t):types.filter(t=>!t.editAs)});const alias=getFieldType(plain?.fieldType)?.editAs;const start=mode==="add"&&preset?preset:null;let name=$state(String(start?.name??plain?.header??""));let fieldType=$state(start?.fieldType??alias?.type??String(plain?.fieldType??"text"));let props=$state(start?{...getFieldType(start.fieldType)?.defaults??{},...start.fieldProps??{}}:{...plain?.fieldProps??{},...alias?.props??{}});if(Array.isArray(props.options))props.options=withOptionIds(props.options);let description=$state(String(plain?.description??""));let search=$state("");let pickerOpen=$state(mode==="add"&&!start);let open=$state(true);const type=$derived(getFieldType(fieldType));const shownTypes=$derived(allowed.filter(t=>!search||t.label.toLowerCase().includes(search.toLowerCase())));const fallbackName=$derived.by(()=>{const base=type?.label??bm("fields.fallbackName");let n=base;for(let i=2;nameTaken(ctrl,n,columnId);i++)n=`${base} ${i}`;return n});const finalName=$derived(name.trim()||(mode==="add"?fallbackName:""));const nameError=$derived(!finalName?bm("fields.nameRequired"):nameTaken(ctrl,finalName,columnId)?bm("fields.nameTaken"):null);const cleared=$derived(mode==="edit"&&columnId?previewChange(ctrl,columnId,{name,fieldType,fieldProps:props}):0);const fromType=plain?.fieldType?String(plain.fieldType):void 0;const warn=$derived(mode==="edit"&&!!fromType&&fromType!==fieldType&&(fieldType!==alias?.type||cleared>0));const optionChange=$derived(mode==="edit"&&columnId?previewOptions(ctrl,columnId,{name,fieldType,fieldProps:props}):null);const touchedNames=$derived(optionChange?[...optionChange.removed,...optionChange.renamed.keys()]:[]);let serverUse=$state.raw(null);const asksServer=!!(ctrl.props.rowModel||ctrl.props.baseFeed);$effect(()=>{const names=touchedNames;const source=ctrl.props.baseSource;if(!asksServer||!source||!names.length||!columnId)return;let gone=false;const multi=fieldType==="multiSelect";const holding=value=>({kind:"fieldFilter",conjunction:"and",conditions:[{column:columnId,kind:multi?"multi":"select",op:multi?"hasAnyOf":"isAnyOf",value:[value]}]});void Promise.all(names.map(n=>source.getRows(feedRequest({expression:holding(n)},{})).then(r=>[n,r.rowCount]))).then(list=>{if(!gone)serverUse=new Map(list)},()=>{});return()=>{gone=true}});const useOfOptions=$derived(asksServer?serverUse:columnId&&touchedNames.length?optionRecords(ctrl,columnId,touchedNames):null);const optionNotes=$derived.by(()=>{const c=optionChange;const use=useOfOptions;if(!c||!use)return[];const notes=[];for(const name2 of c.removed)if(use.get(name2))notes.push(bmCount("fields.optionRemoved",use.get(name2),{name:name2}));if(asksServer){for(const name2 of c.renamed.keys())if(use.get(name2))notes.push(bmCount("fields.optionRenamed",use.get(name2),{name:name2}))}return notes});const optionProblem=$derived.by(()=>{const list=props.options??[];const seen=new Set;for(const o of list){const v=String(o.value??"").trim();if(v&&seen.has(v))return bm("fields.optionsSameName",{name:v});if(v)seen.add(v)}const was=withOptionIds(plain?.fieldProps?.options);const blank=list.find(o=>!String(o.value??"").trim()&&was.some(w=>w.id===o.id));return blank?bm("fields.optionNeedsName",{name:was.find(w=>w.id===blank.id).value}):null});const inputValue=e=>e.currentTarget.value;let searchBox=$state(null);function openPicker(){pickerOpen=true;void tick().then(()=>searchBox?.focus())}function typeSearchKey(e){if(e.key!=="Enter"||e.isComposing)return;e.preventDefault();const first=grouped[0]?.types[0];if(first)pickType(first.id)}function pickType(id){if(id===fieldType)return;fieldType=id;pickerOpen=false;search="";const next=getFieldType(id);const keep={...next?.defaults??{}};for(const p of next?.properties??[])if(props[p.key]!==void 0)keep[p.key]=props[p.key];if(props.editors!==void 0)keep.editors=props.editors;if(props.editorChoices!==void 0&&(next?.id==="singleSelect"||next?.id==="multiSelect"))keep.editorChoices=props.editorChoices;props=keep}const editorCtx=$derived({ctrl,props:{...type?.defaults??{},...props},columns:ctrl.internalColumns.map(c=>originalColumn(c)).filter(c=>defId(c)!==columnId),self:[plain?.field,columnId,plain?.header,finalName]});const shownProps=$derived((type?.properties??[]).filter(p=>!p.visible||p.visible(editorCtx.props)));const formulaProblem=$derived.by(()=>{for(const p of shownProps){if(p.kind!=="formula"&&p.kind!=="prompt")continue;const src=String(editorCtx.props[p.key]??"");const message=!src.trim()?null:p.kind==="prompt"?aiPromptError(src,editorCtx.columns,editorCtx.self):formulaError(src,columnResolver(editorCtx.columns,editorCtx.self));if(message)return bm(p.kind==="prompt"?"fields.fixPromptFirst":"fields.fixFormulaFirst",{message})}return null});const NEEDS={lookup:["linkField","field"],rollup:["linkField","field"],count:["linkField"],ai:["prompt"]};const missing=$derived((NEEDS[fieldType]??[]).find(key=>!String(editorCtx.props[key]??"").trim())??null);const missingText=$derived.by(()=>{if(missing==="prompt")return bm("fields.needPrompt");if(missing==="field")return bm("fields.needLinkedField");return editorCtx.columns.some(c=>c.fieldType==="link")?bm("fields.needLinkField"):bm("fields.needLinkFieldFirst")});let tried=$state(false);const GROUPS=[{id:"basic",key:"fields.groupBasic"},{id:"number",key:"fields.groupNumber"},{id:"date",key:"fields.groupDate"},{id:"people",key:"fields.groupPeople"},{id:"computed",key:"fields.groupComputed"},{id:"relation",key:"fields.groupRelation"}];const groupOf=t=>GROUPS.some(g=>g.id===t.group)?t.group:"basic";const grouped=$derived(GROUPS.map(g=>({...g,types:shownTypes.filter(t=>groupOf(t)===g.id)})).filter(g=>g.types.length));const takesEdits=$derived.by(()=>{try{return type?.fill?.({id:"_",field:"_",fieldType},{...type.defaults??{}},{columns:[]})?.editable!==false}catch{return true}});const editors=$derived(fieldEditors(props));const me=$derived(getCurrentUser());const people=$derived.by(()=>{const list=[...getFieldUsers()];if(me&&!list.some(u=>u.id===me.id))list.unshift(me);for(const id of editors??[])if(!isFieldToken(id)&&!list.some(u=>u.id===id))list.push({id,name:id});return list});const personFields=$derived(editorCtx.columns.filter(c=>c.fieldType==="user"||c.fieldType==="createdBy").map(c=>({key:String(c.field??c.id),name:String(c.header??c.field??c.id)})));const choiceField=$derived(fieldType==="singleSelect"||fieldType==="multiSelect");const choiceList=$derived((props.options??[]).filter(o=>String(o.value??"")!=="").map(o=>({value:String(o.value),label:String(o.label??o.value)})));const heldChoices=$derived(Array.isArray(props.editorChoices)?props.editorChoices.map(String):[]);let choicesOnly=$state(Array.isArray(props.editorChoices)&&props.editorChoices.length>0);function setHeld(list){const{editorChoices:_drop,...rest}=props;props=list.length?{...rest,editorChoices:list}:rest}function holdChoices(on){choicesOnly=on;if(!on)setHeld([])}const toggleChoice=v=>setHeld(heldChoices.includes(v)?heldChoices.filter(x=>x!==v):[...heldChoices,v]);function restrict(on){const{editors:_drop,editorChoices:_held,...rest}=props;if(!on)choicesOnly=false;props=on?{...rest,editors:me?[me.id]:[]}:rest}function toggleEditor(id){const list=editors??[];props={...props,editors:list.includes(id)?list.filter(x=>x!==id):[...list,id]}}function save(){if(nameError||formulaProblem||optionProblem)return;if(missing){const key=missing;tried=true;void tick().then(()=>document.getElementById(`sv-fed-${key}`)?.focus());return}const draft={name:finalName,fieldType,fieldProps:$state.snapshot(props),description};if(mode==="edit"&&columnId)updateField(ctrl,columnId,draft);else addField(ctrl,draft,index);close()}function close(){open=false;onClose()}
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
<SvModal bind:open title={mode === 'edit' ? bm('fields.editorTitleEdit') : bm('fields.editorTitleAdd')} width={500} onClose={close}>
|
|
@@ -104,12 +104,36 @@ import{tick}from"svelte";import{SvModal}from"@svgrid/grid";import PropertyInput
|
|
|
104
104
|
</li>
|
|
105
105
|
{/each}
|
|
106
106
|
</ul>
|
|
107
|
+
{#if personFields.length}
|
|
108
|
+
<span class="sv-fed-sublabel" id="sv-fed-who-fields">{bm('fields.whoeverInLabel')}</span>
|
|
109
|
+
<ul class="sv-fed-people" aria-labelledby="sv-fed-who-fields">
|
|
110
|
+
{#each personFields as f (f.key)}
|
|
111
|
+
<li>
|
|
112
|
+
<label class="sv-fed-person">
|
|
113
|
+
<input type="checkbox" checked={editors.includes(fieldToken(f.key))} onchange={() => toggleEditor(fieldToken(f.key))} />
|
|
114
|
+
<span>{bm('fields.whoeverIn', { field: f.name })}</span>
|
|
115
|
+
</label>
|
|
116
|
+
</li>
|
|
117
|
+
{/each}
|
|
118
|
+
</ul>
|
|
119
|
+
{/if}
|
|
120
|
+
{#if choiceField && choiceList.length}
|
|
121
|
+
<label class="sv-fed-person sv-fed-choices-only"><input type="checkbox" checked={choicesOnly} onchange={(e) => holdChoices(e.currentTarget.checked)} /> <span>{bm('fields.onlySomeChoices')}</span></label>
|
|
122
|
+
{#if choicesOnly}
|
|
123
|
+
<ul class="sv-fed-people" aria-label={bm('fields.heldChoices')}>
|
|
124
|
+
{#each choiceList as o (o.value)}
|
|
125
|
+
<li><label class="sv-fed-person"><input type="checkbox" checked={heldChoices.includes(o.value)} onchange={() => toggleChoice(o.value)} /> <span>{o.label}</span></label></li>
|
|
126
|
+
{/each}
|
|
127
|
+
</ul>
|
|
128
|
+
{#if !heldChoices.length}<p class="sv-fed-hint-line">{bm('fields.pickHeldChoices')}</p>{/if}
|
|
129
|
+
{/if}
|
|
130
|
+
{/if}
|
|
107
131
|
{#if !editors.length}
|
|
108
|
-
<p class="sv-fed-hint-line">{bm('fields.nobodyCanChange')}</p>
|
|
109
|
-
{:else if me && !editors.includes(me.id)}
|
|
110
|
-
<p class="sv-fed-hint-line">{bm('fields.youCannotChange')}</p>
|
|
132
|
+
<p class="sv-fed-hint-line">{bm(heldChoices.length ? 'fields.nobodyCanPick' : 'fields.nobodyCanChange')}</p>
|
|
133
|
+
{:else if me && !editors.includes(me.id) && !ruleFields(editors).length}
|
|
134
|
+
<p class="sv-fed-hint-line">{bm(heldChoices.length ? 'fields.youCannotPick' : 'fields.youCannotChange')}</p>
|
|
111
135
|
{/if}
|
|
112
|
-
<p class="sv-fed-hint-line">{bm('fields.othersReadOnly')}</p>
|
|
136
|
+
<p class="sv-fed-hint-line">{bm(heldChoices.length ? 'fields.othersPickRest' : 'fields.othersReadOnly')}</p>
|
|
113
137
|
{/if}
|
|
114
138
|
</div>
|
|
115
139
|
{/if}
|
|
@@ -150,5 +174,5 @@ import{tick}from"svelte";import{SvModal}from"@svgrid/grid";import PropertyInput
|
|
|
150
174
|
</SvModal>
|
|
151
175
|
|
|
152
176
|
<style>
|
|
153
|
-
.sv-fed{display:flex;flex-direction:column;gap:18px}.sv-fed-group{display:flex;flex-direction:column;gap:6px}.sv-fed-props{gap:10px;padding:12px;border-radius:var(--sg-radius, 6px);background:var(--sg-header-bg, #f8fafc);border:1px solid var(--sg-border, #e2e8f0)}.sv-fed-label{font-size:12px;font-weight:600;color:var(--sg-fg, #0f172a)}.sv-fed-optional{font-weight:400;color:var(--sg-muted, #64748b)}.sv-fed-input{width:100%;box-sizing:border-box;height:34px;padding:0 10px;font:inherit;font-size:14px;border:1px solid var(--sg-input-border, var(--sg-border, #e2e8f0));border-radius:var(--sg-radius, 6px);background:var(--sg-input-bg, var(--sg-bg, #fff));color:var(--sg-fg, #0f172a);transition:border-color .12s ease,box-shadow .12s ease}.sv-fed-input::placeholder{color:var(--sg-muted, #94a3b8)}.sv-fed-input:focus{outline:none;border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 22%,transparent)}.sv-fed-input[aria-invalid=true]{border-color:var(--sg-danger, #dc2626)}.sv-fed-desc{height:auto;min-height:58px;padding:8px 10px;resize:vertical;line-height:1.4}.sv-fed-error{margin:0;font-size:12px;color:var(--sg-danger, #dc2626)}.sv-fed-search{position:relative;display:flex;align-items:center;color:var(--sg-muted, #64748b)}.sv-fed-search svg{position:absolute;inset-inline-start:10px;pointer-events:none}.sv-fed-search .sv-fed-input{height:30px;padding-inline-start:30px;font-size:13px}.sv-fed-current{display:flex;align-items:center;gap:10px;width:100%;height:38px;padding:0 10px;border:1px solid var(--sg-input-border, var(--sg-border, #e2e8f0));border-radius:var(--sg-radius, 6px);background:var(--sg-input-bg, var(--sg-bg, #fff));color:var(--sg-fg, #0f172a);font:inherit;font-size:14px;text-align:start;cursor:pointer}.sv-fed-current:hover{border-color:var(--sg-muted, #94a3b8)}.sv-fed-current:focus-visible{outline:none;border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 22%,transparent)}.sv-fed-current .sv-fed-type-label{flex:1}.sv-fed-chevron{flex:none;color:var(--sg-muted, #64748b)}.sv-fed-types-scroll{max-height:300px;overflow:auto;margin-top:2px;padding-inline-end:2px}.sv-fed-types{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2px}.sv-fed-type-group{margin:10px 0 4px;font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-fed-type-group:first-child{margin-top:2px}.sv-fed-type{display:flex;align-items:center;gap:10px;height:34px;padding:0 8px;border:1px solid transparent;border-radius:var(--sg-radius, 6px);background:none;color:var(--sg-fg, #0f172a);font:inherit;font-size:13px;text-align:start;cursor:pointer}.sv-fed-type:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fed-type.is-on{background:var(--sg-selection-bg, #eef4ff);border-color:var(--sg-accent, #2563eb)}.sv-fed-type:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:1px}.sv-fed-type-icon{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:6px;background:var(--sg-header-bg, #f8fafc);border:1px solid var(--sg-border, #e2e8f0);color:var(--sg-muted, #64748b)}.sv-fed-type.is-on .sv-fed-type-icon{color:var(--sg-accent, #2563eb);border-color:color-mix(in srgb,var(--sg-accent, #2563eb) 40%,transparent)}.sv-fed-type-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-fed-none{grid-column:1 / -1;margin:8px 0;font-size:13px;color:var(--sg-muted, #64748b)}.sv-fed-who{display:flex;flex-direction:column;gap:4px}.sv-fed-who-opt,.sv-fed-person{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--sg-fg, #0f172a);cursor:pointer}.sv-fed-people{margin:2px 0 0;padding:6px 8px;list-style:none;max-height:168px;overflow:auto;display:flex;flex-direction:column;gap:4px;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px)}.sv-fed-hint-line{margin:2px 0 0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fed-warning{display:flex;gap:8px;align-items:flex-start;margin:0;padding:10px 12px;border-radius:var(--sg-radius, 6px);font-size:13px;line-height:1.4;color:var(--sg-fg, #0f172a);background:color-mix(in srgb,var(--sg-warning, #f59e0b) 14%,transparent);border:1px solid color-mix(in srgb,var(--sg-warning, #f59e0b) 35%,transparent)}.sv-fed-warning svg{flex:none;margin-top:1px;color:var(--sg-warning, #d97706)}.sv-fed-foot{display:flex;flex-direction:column;gap:8px;width:100%;max-height:40vh;overflow:auto}.sv-fed-footer{display:flex;justify-content:flex-end;gap:8px;width:100%}.sv-fed-btn{min-height:34px;padding:6px 16px;font:inherit;font-size:13px;font-weight:500;cursor:pointer;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px);background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a)}.sv-fed-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fed-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-fed-btn.is-primary{background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);border-color:var(--sg-fg, #0f172a)}.sv-fed-btn.is-primary:hover{opacity:.9}.sv-fed-btn:disabled{opacity:.4;cursor:not-allowed}
|
|
177
|
+
.sv-fed{display:flex;flex-direction:column;gap:18px}.sv-fed-group{display:flex;flex-direction:column;gap:6px}.sv-fed-props{gap:10px;padding:12px;border-radius:var(--sg-radius, 6px);background:var(--sg-header-bg, #f8fafc);border:1px solid var(--sg-border, #e2e8f0)}.sv-fed-label{font-size:12px;font-weight:600;color:var(--sg-fg, #0f172a)}.sv-fed-optional{font-weight:400;color:var(--sg-muted, #64748b)}.sv-fed-input{width:100%;box-sizing:border-box;height:34px;padding:0 10px;font:inherit;font-size:14px;border:1px solid var(--sg-input-border, var(--sg-border, #e2e8f0));border-radius:var(--sg-radius, 6px);background:var(--sg-input-bg, var(--sg-bg, #fff));color:var(--sg-fg, #0f172a);transition:border-color .12s ease,box-shadow .12s ease}.sv-fed-input::placeholder{color:var(--sg-muted, #94a3b8)}.sv-fed-input:focus{outline:none;border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 22%,transparent)}.sv-fed-input[aria-invalid=true]{border-color:var(--sg-danger, #dc2626)}.sv-fed-desc{height:auto;min-height:58px;padding:8px 10px;resize:vertical;line-height:1.4}.sv-fed-error{margin:0;font-size:12px;color:var(--sg-danger, #dc2626)}.sv-fed-search{position:relative;display:flex;align-items:center;color:var(--sg-muted, #64748b)}.sv-fed-search svg{position:absolute;inset-inline-start:10px;pointer-events:none}.sv-fed-search .sv-fed-input{height:30px;padding-inline-start:30px;font-size:13px}.sv-fed-current{display:flex;align-items:center;gap:10px;width:100%;height:38px;padding:0 10px;border:1px solid var(--sg-input-border, var(--sg-border, #e2e8f0));border-radius:var(--sg-radius, 6px);background:var(--sg-input-bg, var(--sg-bg, #fff));color:var(--sg-fg, #0f172a);font:inherit;font-size:14px;text-align:start;cursor:pointer}.sv-fed-current:hover{border-color:var(--sg-muted, #94a3b8)}.sv-fed-current:focus-visible{outline:none;border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 22%,transparent)}.sv-fed-current .sv-fed-type-label{flex:1}.sv-fed-chevron{flex:none;color:var(--sg-muted, #64748b)}.sv-fed-types-scroll{max-height:300px;overflow:auto;margin-top:2px;padding-inline-end:2px}.sv-fed-types{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2px}.sv-fed-type-group{margin:10px 0 4px;font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-fed-type-group:first-child{margin-top:2px}.sv-fed-type{display:flex;align-items:center;gap:10px;height:34px;padding:0 8px;border:1px solid transparent;border-radius:var(--sg-radius, 6px);background:none;color:var(--sg-fg, #0f172a);font:inherit;font-size:13px;text-align:start;cursor:pointer}.sv-fed-type:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fed-type.is-on{background:var(--sg-selection-bg, #eef4ff);border-color:var(--sg-accent, #2563eb)}.sv-fed-type:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:1px}.sv-fed-type-icon{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:6px;background:var(--sg-header-bg, #f8fafc);border:1px solid var(--sg-border, #e2e8f0);color:var(--sg-muted, #64748b)}.sv-fed-type.is-on .sv-fed-type-icon{color:var(--sg-accent, #2563eb);border-color:color-mix(in srgb,var(--sg-accent, #2563eb) 40%,transparent)}.sv-fed-type-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-fed-none{grid-column:1 / -1;margin:8px 0;font-size:13px;color:var(--sg-muted, #64748b)}.sv-fed-who{display:flex;flex-direction:column;gap:4px}.sv-fed-who-opt,.sv-fed-person{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--sg-fg, #0f172a);cursor:pointer}.sv-fed-sublabel{display:block;margin-top:8px;font-size:12px;font-weight:600;color:var(--sg-muted, #64748b)}.sv-fed-choices-only{margin-top:8px}.sv-fed-people{margin:2px 0 0;padding:6px 8px;list-style:none;max-height:168px;overflow:auto;display:flex;flex-direction:column;gap:4px;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px)}.sv-fed-hint-line{margin:2px 0 0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fed-warning{display:flex;gap:8px;align-items:flex-start;margin:0;padding:10px 12px;border-radius:var(--sg-radius, 6px);font-size:13px;line-height:1.4;color:var(--sg-fg, #0f172a);background:color-mix(in srgb,var(--sg-warning, #f59e0b) 14%,transparent);border:1px solid color-mix(in srgb,var(--sg-warning, #f59e0b) 35%,transparent)}.sv-fed-warning svg{flex:none;margin-top:1px;color:var(--sg-warning, #d97706)}.sv-fed-foot{display:flex;flex-direction:column;gap:8px;width:100%;max-height:40vh;overflow:auto}.sv-fed-footer{display:flex;justify-content:flex-end;gap:8px;width:100%}.sv-fed-btn{min-height:34px;padding:6px 16px;font:inherit;font-size:13px;font-weight:500;cursor:pointer;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px);background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a)}.sv-fed-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fed-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-fed-btn.is-primary{background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);border-color:var(--sg-fg, #0f172a)}.sv-fed-btn.is-primary:hover{opacity:.9}.sv-fed-btn:disabled{opacity:.4;cursor:not-allowed}
|
|
154
178
|
</style>
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import{fieldToken}from"./people-rule";import{getCurrentUser,getFieldUsers}from"./sources.svelte";import UserFace from"./UserFace.svelte";import{bm}from"./messages.svelte";let{value,fields=[],everyone,only,name,onChange}=$props();const me=$derived(getCurrentUser());const people=$derived.by(()=>{const list=[...getFieldUsers()];if(me&&!list.some(u=>u.id===me.id))list.unshift(me);return list});const rule=$derived(value?[...value]:null);const narrow=on=>onChange(on?me?[me.id]:[]:void 0);function toggle(entry){const list=rule??[];onChange(list.includes(entry)?list.filter(x=>x!==entry):[...list,entry])}
|
|
3
|
+
</script>
|
|
4
|
+
|
|
5
|
+
<div class="sv-prp" role="radiogroup" aria-label={only}>
|
|
6
|
+
<label class="sv-prp-opt"><input type="radio" {name} checked={!rule} onchange={() => narrow(false)} /> {everyone}</label>
|
|
7
|
+
<label class="sv-prp-opt"><input type="radio" {name} checked={!!rule} onchange={() => narrow(true)} /> {only}</label>
|
|
8
|
+
</div>
|
|
9
|
+
{#if rule}
|
|
10
|
+
<ul class="sv-prp-list" aria-label={only}>
|
|
11
|
+
{#each people as u (u.id)}
|
|
12
|
+
<li>
|
|
13
|
+
<label class="sv-prp-opt">
|
|
14
|
+
<input type="checkbox" checked={rule.includes(u.id)} onchange={() => toggle(u.id)} />
|
|
15
|
+
<UserFace user={u} size={18} />
|
|
16
|
+
<span>{u.id === me?.id ? bm('fields.nameYou', { name: u.name }) : u.name}</span>
|
|
17
|
+
</label>
|
|
18
|
+
</li>
|
|
19
|
+
{/each}
|
|
20
|
+
{#each fields as f (f.key)}
|
|
21
|
+
<li>
|
|
22
|
+
<label class="sv-prp-opt">
|
|
23
|
+
<input type="checkbox" checked={rule.includes(fieldToken(f.key))} onchange={() => toggle(fieldToken(f.key))} />
|
|
24
|
+
<span>{bm('fields.whoeverIn', { field: f.name })}</span>
|
|
25
|
+
</label>
|
|
26
|
+
</li>
|
|
27
|
+
{/each}
|
|
28
|
+
</ul>
|
|
29
|
+
{#if !rule.length}<p class="sv-prp-hint">{bm('fields.whoNobody')}</p>{/if}
|
|
30
|
+
{/if}
|
|
31
|
+
|
|
32
|
+
<style>
|
|
33
|
+
.sv-prp{display:flex;flex-direction:column;gap:4px}.sv-prp-opt{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--sg-fg, #0f172a);cursor:pointer}.sv-prp-list{list-style:none;margin:6px 0 0;padding:6px 8px;max-height:180px;overflow:auto;display:flex;flex-direction:column;gap:4px;border:1px solid var(--sg-border, #e2e8f0);border-radius:6px}.sv-prp-hint{margin:4px 0 0;font-size:12px;color:var(--sg-muted, #64748b)}
|
|
34
|
+
</style>
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type $$ComponentProps = {
|
|
2
|
+
value: ReadonlyArray<string> | undefined;
|
|
3
|
+
/** The record's person fields a rule can name: their key and name. */
|
|
4
|
+
fields?: ReadonlyArray<{
|
|
5
|
+
key: string;
|
|
6
|
+
name: string;
|
|
7
|
+
}>;
|
|
8
|
+
everyone: string;
|
|
9
|
+
only: string;
|
|
10
|
+
/** The radio group's name, one per picker on the page. */
|
|
11
|
+
name: string;
|
|
12
|
+
onChange: (rule: string[] | undefined) => void;
|
|
13
|
+
};
|
|
14
|
+
declare const PeopleRulePicker: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
15
|
+
type PeopleRulePicker = ReturnType<typeof PeopleRulePicker>;
|
|
16
|
+
export default PeopleRulePicker;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import OptionsEditor from"./OptionsEditor.svelte";import{columnResolver,formulaError}from"./formula";import FormulaInput from"./FormulaInput.svelte";import{aiPromptError}from"./ai-prompt";import{getFieldUsers}from"./sources.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{bm}from"./messages.svelte";let{def,value,fieldType,ctx,onChange}=$props();const id=$derived(`sv-fed-${def.key}`);const choices=$derived(def.kind==="choice"?typeof def.choices==="function"?def.choices(ctx):def.choices:[]);const names=$derived(ctx.columns.map(c=>String(c.header??c.field??"")).filter(Boolean));const formulaMessage=$derived(!String(value??"").trim()?null:def.kind==="formula"?formulaError(String(value),columnResolver(ctx.columns,ctx.self)):def.kind==="prompt"?aiPromptError(String(value),ctx.columns,ctx.self):null);const areaPlaceholder=$derived(def.kind==="prompt"?def.placeholder??"":bm("fields.formulaPlaceholder"));const selectOptions=$derived((ctx.props.options??[]).map(o=>String(o.value)).filter(Boolean));let formulaEl=$state(null);const valuesTables=$derived(def.kind==="recordValues"?ctx.ctrl?.props?.baseTables?.()??[]:[]);const valuesTable=$derived(valuesTables.find(t=>t.id===ctx.ctrl?.props?.baseTableId)??null);const valuesStand={id:"button",name:"",enabled:true,trigger:{type:"recordCreated"},actions:[]};const inputValue=e=>e.currentTarget.value;const checkedOf=e=>e.currentTarget.checked;const numberOf=e=>{const raw=inputValue(e);return raw===""?void 0:Number(raw)};function insertField(name){const token=`{${name}}`;const el=formulaEl;const text=String(value??"");if(!el)return onChange(text+token);const at=el.selectionStart??text.length;onChange(text.slice(0,at)+token+text.slice(el.selectionEnd??at));queueMicrotask(()=>{el.focus();el.setSelectionRange(at+token.length,at+token.length)})}const toggleIn=(list,v)=>{const arr=Array.isArray(list)?list:[];return arr.includes(v)?arr.filter(x=>x!==v):[...arr,v]};
|
|
2
|
+
import OptionsEditor from"./OptionsEditor.svelte";import{columnResolver,formulaError}from"./formula";import FormulaInput from"./FormulaInput.svelte";import{aiPromptError}from"./ai-prompt";import{getFieldUsers}from"./sources.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import PeopleRulePicker from"./PeopleRulePicker.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{bm}from"./messages.svelte";let{def,value,fieldType,ctx,onChange}=$props();const id=$derived(`sv-fed-${def.key}`);const choices=$derived(def.kind==="choice"?typeof def.choices==="function"?def.choices(ctx):def.choices:[]);const names=$derived(ctx.columns.map(c=>String(c.header??c.field??"")).filter(Boolean));const formulaMessage=$derived(!String(value??"").trim()?null:def.kind==="formula"?formulaError(String(value),columnResolver(ctx.columns,ctx.self)):def.kind==="prompt"?aiPromptError(String(value),ctx.columns,ctx.self):null);const areaPlaceholder=$derived(def.kind==="prompt"?def.placeholder??"":bm("fields.formulaPlaceholder"));const selectOptions=$derived((ctx.props.options??[]).map(o=>String(o.value)).filter(Boolean));let formulaEl=$state(null);const valuesTables=$derived(def.kind==="recordValues"?ctx.ctrl?.props?.baseTables?.()??[]:[]);const valuesTable=$derived(valuesTables.find(t=>t.id===ctx.ctrl?.props?.baseTableId)??null);const valuesStand={id:"button",name:"",enabled:true,trigger:{type:"recordCreated"},actions:[]};const inputValue=e=>e.currentTarget.value;const checkedOf=e=>e.currentTarget.checked;const numberOf=e=>{const raw=inputValue(e);return raw===""?void 0:Number(raw)};function insertField(name){const token=`{${name}}`;const el=formulaEl;const text=String(value??"");if(!el)return onChange(text+token);const at=el.selectionStart??text.length;onChange(text.slice(0,at)+token+text.slice(el.selectionEnd??at));queueMicrotask(()=>{el.focus();el.setSelectionRange(at+token.length,at+token.length)})}const toggleIn=(list,v)=>{const arr=Array.isArray(list)?list:[];return arr.includes(v)?arr.filter(x=>x!==v):[...arr,v]};
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
{#if def.kind === 'checkbox'}
|
|
@@ -18,6 +18,17 @@ import OptionsEditor from"./OptionsEditor.svelte";import{columnResolver,formulaE
|
|
|
18
18
|
<div class="sv-pi-box">
|
|
19
19
|
<FilterPanel ctrl={ctx.ctrl} value={value ?? null} title="" empty={bm('fields.buttonWhenAlways')} onChange={(f: FieldFilter) => onChange(f.conditions?.length ? f : undefined)} />
|
|
20
20
|
</div>
|
|
21
|
+
{:else if def.kind === 'people'}
|
|
22
|
+
<span class="sv-pi-label">{def.label}</span>
|
|
23
|
+
<PeopleRulePicker
|
|
24
|
+
name={`sv-pi-${def.key}`}
|
|
25
|
+
value={Array.isArray(value) ? (value as string[]) : undefined}
|
|
26
|
+
fields={ctx.columns.filter((c) => c.fieldType === 'user' || c.fieldType === 'createdBy').map((c) => ({ key: String(c.field ?? c.id), name: String(c.header ?? c.field ?? c.id) }))}
|
|
27
|
+
everyone={def.everyone}
|
|
28
|
+
only={def.only}
|
|
29
|
+
{onChange}
|
|
30
|
+
/>
|
|
31
|
+
{#if def.hint}<p class="sv-pi-hint">{def.hint}</p>{/if}
|
|
21
32
|
{:else if def.kind === 'recordValues'}
|
|
22
33
|
<span class="sv-pi-label">{def.label}</span>
|
|
23
34
|
{#if def.hint}<p class="sv-pi-hint">{def.hint}</p>{/if}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{recordActionsFor}from"./record-actions";import{commentSnippets}from"./comment-snippets.svelte";import{onDestroy,onMount,tick,untrack}from"svelte";import{commentDraftsOf,getRecordRequest,holdForRecordEditor}from"./editor-request.svelte";import{SvModal,announce,toast}from"@svgrid/grid";import FieldInput from"./FieldInput.svelte";import{fieldPropsOf,getFieldType,originalColumn}from"./registry.svelte";import{protectionText}from"./field-access.svelte";import{isReadOnlyGrid}from"./base-share";import{canCommentIn,canDeleteIn}from"./base-permissions";import{askDeleteRecord}from"./record-delete.svelte";import{cellText,dataRows,fieldColumns,leafFilter,primaryIdOf}from"./grid-access";import{recordWalkOf}from"./record-walk";import{addComment,commentStoreTakes,commentsOf,deleteComment,editComment,historyOf,historyState,loadHistory,markSeen,ownsComment,timeAgo,unseenOf}from"./activity.svelte";import{uploadAttachment}from"./attachments";import{findFieldUser}from"./sources.svelte";import{encodeMentions,mentionText,parseMentions}from"./mentions";import MentionInput from"./MentionInput.svelte";import{dictationSupported,dictate,withSaid}from"./dictation.svelte";import UserFace from"./UserFace.svelte";import{recordProposalsFor}from"../review/card-marks.svelte";import{bm,bmCount}from"./messages.svelte";let{ctrl,rowId,editPrimary=false,focus,onClose}=$props();let current=$state(rowId);let open=$state(true);let editing=$state(null);let showHidden=$state(false);let comment=$state("");let picked=$state([]);const rows=$derived(ctrl.allRows??[]);let lastAt=-1;function rowIndexOf(list,id){if(id==null)return-1;for(const near of[lastAt,untrack(()=>ctrl.activeCell?.rowIndex??-1)]){if(near<0)continue;for(let d=0;d<=200;d++){if(list[near+d]?.id===id)return lastAt=near+d;if(d&&near-d>=0&&list[near-d]?.id===id)return lastAt=near-d}}return lastAt=list.findIndex(r=>r.id===id)}const index=$derived(rowIndexOf(rows,current));const row=$derived(index>=0?rows[index]:null);const isDraft=$derived(!!ctrl.props?.baseIsDraft?.(current));let lastIndex=0;const at=$derived.by(()=>{if(index>=0)lastIndex=index;return lastIndex});const walk=$derived(recordWalkOf(ctrl));const model=$derived(ctrl.props?.rowModel);const grouped=$derived((ctrl.groupingColumns??[]).length>0);const notRead=r=>String(r.id).startsWith("sv-ph:");function isRecord(r){const kind=r.original?.__group?.kind;return kind?kind==="leaf":r.__treeRow||!(typeof r.getCanExpand==="function"&&r.getCanExpand())}function rowFrom(from,by){for(let i=from+by;i>=0&&i<rows.length;i+=by){const r=rows[i];if(notRead(r)||isRecord(r))return i}return-1}function rowBeside(by){const seen=at;return rowFrom(index>=0?index:by>0?seen-1:seen,by)}let located=$state(0);const walkPlace=$derived(walk&&!isDraft?(void located,walk.place(current)):null);let lastPlace=-1;const walkAt=$derived.by(()=>{if(walkPlace!=null)lastPlace=walkPlace;return lastPlace});const walkFrom=by=>walkPlace!=null?walkAt:by>0?walkAt-1:walkAt;const canPrev=$derived(walk?walkAt>=0&&walk.has(walkFrom(-1),-1):rowBeside(-1)>=0);const canNext=$derived(walk?walkAt>=0&&walk.has(walkFrom(1),1):rowBeside(1)>=0);const records=$derived(!model&&grouped?dataRows(ctrl):null);const total=$derived(walk?walk.total():model?.getState?model.recordCount?.()??model.getState().rowCount??rows.length:(records??rows).length);const locale=$derived(ctrl.props?.localization?.locale);const place=$derived.by(()=>{if(isDraft)return null;if(walk)return walkPlace;if(index<0)return null;if(model)return grouped||model.isPinned?.(current)?null:index-Math.max(0,rows.length-total);return records?records.findIndex(r=>r.id===current):index});const positionText=$derived.by(()=>{if(isDraft)return bm("record.newRecord");if(!walk&&index<0)return bmCount("record.notInView",total,{count:total.toLocaleString(locale)});if(place==null)return bmCount("viewbar.records",total);return bm("record.position",{index:(place+1).toLocaleString(locale),total:total.toLocaleString(locale)})});const filteredOut=$derived.by(()=>{if(!row)return false;const keep=leafFilter(ctrl);return!!keep&&!keep(row)});const columns=$derived((ctrl.allColumns??[]).filter(c=>!c.id.startsWith("__")&&(c.columnDef.field!=null||c.columnDef.fieldFn!=null)));const hidden=$derived.by(()=>{const shownIds=new Set(columns.map(c=>c.id));return fieldColumns(ctrl).filter(c=>!shownIds.has(c.id)).map(c=>({id:c.id,columnDef:c.def}))});function valueOf(c){if(!row)return void 0;const base=c.columnDef.fieldFn?c.columnDef.fieldFn(row.original):row.original?.[c.columnDef.field];return ctrl.getCellDisplayValue(row.id,c.id,columns.includes(c)?row.getCellValueByColumnId(c.id):base)}const asField=c=>({id:c.id,field:String(c.columnDef.field??c.id),header:label(c),fieldType:c.columnDef.fieldType,def:c.columnDef,visible:true});const primaryId=$derived(primaryIdOf(ctrl));const primary=$derived(columns.find(c=>c.id===primaryId)??columns.find(c=>c.columnDef.fieldType==="text"||!c.columnDef.fieldType&&c.columnDef.editorType==null)??columns[0]);const title=$derived(row&&primary?cellText(asField(primary),valueOf(primary),row)||bm("record.untitled"):bm("record.record"));function label(c){return typeof c.columnDef.header==="string"?c.columnDef.header:c.id}const protectionOf=c=>c.columnDef.fieldType?protectionText(originalColumn(c.columnDef),fieldPropsOf(originalColumn(c.columnDef))):null;const iconOf=c=>c.columnDef.fieldType?getFieldType(c.columnDef.fieldType)?.icon:void 0;function editable(c){if(!row||!ctrl.editingEnabled)return false;const ci=ctrl.allColumns.findIndex(x=>x.id===c.id);if(ci<0)return false;return ctrl.isCellEditableAt?!!ctrl.isCellEditableAt(index,ci):c.columnDef.editable!==false}const editorOpen=$derived(editing!=null);$effect(()=>{if(editorOpen)return untrack(holdForRecordEditor)});onMount(()=>{if(editPrimary&&primary&&editable(primary))editing=primary.id});let settled=$state(false);const settling=setTimeout(()=>settled=true,400);onDestroy(()=>{clearTimeout(settling);walk?.stop?.()});let locating=null;$effect(()=>{const w=walk;const r=row;if(!w?.locate||!r||isDraft||walkPlace!=null||locating===r.id)return;locating=r.id;untrack(()=>void w.locate(r.id,r.original).finally(()=>located+=1))});let commentBox=$state(null);const commentFocusFor=r=>r?.focus==="comment"&&r.ctrl===ctrl;const initialFocus=()=>focus==="comment"||commentFocusFor(getRecordRequest())?commentBox:null;$effect(()=>{const r=getRecordRequest();if(!commentFocusFor(r))return;untrack(()=>{if(r.rowId!==current)current=r.rowId;queueMicrotask(()=>commentBox?.focus())})});let listening=$state(null);const speakable=c=>dictationSupported()&&(c.columnDef.fieldType==="text"||c.columnDef.fieldType==="longText");async function speakInto(c){if(listening)return;listening=c.id;try{const said=await dictate();if(said)commit(c,withSaid(row?.getCellValueByColumnId?.(c.id),said,c.columnDef.fieldType==="longText"))}finally{listening=null}}async function speakComment(){if(listening)return;listening=":comment";try{const said=await dictate();if(said)comment=withSaid(comment,said,false)}finally{listening=null}}function commit(c,v){editing=null;if(!row||v===void 0)return;const none=x=>x==null||x===""||Array.isArray(x)&&!x.length;if(none(v)&&none(row.getCellValueByColumnId?.(c.id)))return;const at2=rowIndexOf(ctrl.allRows,current);if(at2<0||!ctrl.startEditing(at2,c.id))return;ctrl.updateEditingCellValue(v);ctrl.saveEditingCell()}let fieldsBox=$state(null);const focusField=id=>[...fieldsBox?.querySelectorAll("[data-frv-field]")??[]].find(el=>el.dataset.frvField===id)?.querySelector(".sv-frv-open")?.focus();function stopEditing(c){editing=null;setTimeout(()=>{const now=document.activeElement;if(editing==null&&(!now||now===document.body||now.getAttribute("role")==="dialog"))focusField(c.id)},0)}const typedInto=c=>["text","number","textarea","fieldNumber","fieldTime",void 0].includes(c.columnDef.editorType);function escapeBox(e){if(e.key!=="Escape"||e.isComposing)return;if((unsaved||deletingNote!=null)&&editing==null)return escapeComment(e);const c=editing!=null?columns.find(x=>x.id===editing):void 0;if(!c||!(typedInto(c)||c.columnDef.editorType==="fieldRating"))return;e.stopPropagation();stopEditing(c)}function editBeside(c,dir){const at2=columns.findIndex(x=>x.id===c.id);for(let i=at2+dir;i>=0&&i<columns.length;i+=dir){const next=columns[i];if(!editable(next)||next.columnDef.editorType==="checkbox")continue;if(typedInto(next))editing=next.id;else{editing=null;void tick().then(()=>focusField(next.id))}return}}let awaited=$state(null);let awaitedRow=$state(null);let stepping=false;let pressed=0;function arrived(){stepping=false;if(!pressed)return;const by=pressed>0?1:-1;pressed-=by;queueMicrotask(()=>void go(by))}$effect(()=>{const id=awaited;if(id!=null&&rowIndexOf(rows,id)>=0)untrack(()=>{current=id;awaited=null;arrived()})});$effect(()=>{const at2=awaitedRow;const r=at2==null?void 0:rows[at2];if(r&&!notRead(r))untrack(()=>{awaitedRow=null;lastAt=at2;if(isRecord(r))current=r.id;arrived()})});let swipeAt=null;function swipeStart(e){const t=e.touches[0];const from=e.target;const busy=!!from?.closest?.('input, textarea, select, [contenteditable="true"], .sv-frv-files, [data-no-swipe]');swipeAt=e.touches.length===1&&t&&!busy?{x:t.clientX,y:t.clientY,t:Date.now()}:null}function swipeEnd(e){const s0=swipeAt;swipeAt=null;const t=e.changedTouches[0];if(!s0||!t||editing!=null)return;const dx=t.clientX-s0.x;const dy=t.clientY-s0.y;if(Math.abs(dx)<70||Math.abs(dx)<Math.abs(dy)*1.8||Date.now()-s0.t>700)return;if(dx<0&&canNext)void go(1);else if(dx>0&&canPrev)void go(-1)}function keepInSight(e){const el=e.target;if(!el?.matches?.('input, textarea, [contenteditable="true"]')||typeof window==="undefined"||window.innerWidth>600)return;setTimeout(()=>el.scrollIntoView?.({block:"center",behavior:"smooth"}),320)}async function go(by){if(stepping){pressed+=by;return}if(editingNote!=null){stepHeld=true;announce(bm("record.commentHoldsStep"));editBox?.focus();return}editing=null;if(walk){stepping=true;const id=await walk.step(walkFrom(by),by);if(id==null){stepping=false;pressed=0;return}awaited=id;setTimeout(()=>{if(awaited!==id)return;awaited=null;stepping=false;pressed=0},3e3);return}const to=rowBeside(by);if(to<0)return;const next=rows[to];if(!notRead(next)){lastAt=to;current=next.id;return}stepping=true;awaitedRow=to;ctrl.buildApi?.().scrollToRow?.(to)}const allCols=$derived([...columns,...hidden]);const feed=$derived.by(()=>{if(!row)return[];const edits=historyOf(ctrl,row.id).map((ch,i)=>{if(ch.added)return{key:`a${ch.at}-${i}`,at:ch.at,by:ch.by,remote:true,kind:"added",field:"",text:""};const c=allCols.find(x=>x.id===ch.columnId);const show=v=>c?cellText(asField(c),v,row):String(v??"");return{key:`e${ch.at}${ch.columnId}-${i}`,at:ch.at,by:ch.by,automation:ch.automation,via:ch.via,through:ch.through,remote:ch.remote,undone:ch.undone,redone:ch.redone,kind:"edit",field:c?label(c):ch.columnId,text:show(ch.value),..."from"in ch&&show(ch.from)?{from:show(ch.from)}:{}}});const notes=commentsOf(ctrl,row.id).map(n=>({key:n.id,at:n.at,by:n.by,kind:"comment",field:"",text:n.text,parts:parseMentions(n.text),note:n}));return[...edits,...notes].sort((a,b)=>a.at-b.at)});const person=item=>item.by?findFieldUser(item.by)?.name??bm("record.someone"):item.remote?bm("record.someoneElse"):bm("record.you");const who=item=>item.automation?bm("record.byAutomation",{name:item.automation}):item.via?bm("record.acceptedBy",{source:item.via,person:person(item)}):item.through?bm("record.through",{person:person(item),source:item.through}):person(item);const shownId=$derived(row?.id);$effect(()=>{const id=shownId;if(id!=null)untrack(()=>loadHistory(ctrl,id))});const history=$derived(row?historyState(ctrl,row.id):{loading:false});$effect(()=>{const id=row?.id;if(id!=null&&unseenOf(ctrl,id))untrack(()=>markSeen(ctrl,id))});const proposals=$derived(row?recordProposalsFor(ctrl.props?.getRowId,row.original,row.id):null);const proposalOf=c=>proposals?.list.find(p=>p.field===String(c.columnDef.field??c.id));const proposedText=(c,p)=>cellText(asField(c),p.after,row)||proposals?.messages.empty||"";let deciding=$state(false);async function decide(ids,how){if(!proposals||deciding||!ids.length)return;deciding=true;try{await(how==="accept"?proposals.accept(ids):proposals.reject(ids))}finally{deciding=false}}const readOnly=$derived(isReadOnlyGrid(ctrl));const canComment=$derived(canCommentIn(ctrl));const takesFiles=$derived(commentStoreTakes("files"));const takesInternal=$derived(commentStoreTakes("internal"));let commentFiles=$state([]);let uploading=$state(0);let internalNote=$state(false);let fileInput=$state(null);const canSend=$derived((!!comment.trim()||commentFiles.length>0)&&uploading===0);async function attach(list){if(!list||!row)return;const forRow=row.id;for(const file of Array.from(list)){uploading+=1;try{const done=await uploadAttachment(file,{},{row:row?.original,columnId:"",signal:new AbortController().signal,onProgress:()=>{}});if(row?.id===forRow)commentFiles=[...commentFiles,done]}catch(e){toast.error(bm("record.commentUploadFailed",{name:file.name,error:e instanceof Error?e.message:String(e)}))}finally{uploading-=1}}if(fileInput)fileInput.value=""}const snippets=$derived(commentSnippets());let repliesOpen=$state(false);let replies=$state(null);let repliesError=$state("");let replyQuery=$state("");let replyName=$state("");let naming=$state(false);const shownReplies=$derived((replies??[]).filter(r=>!replyQuery.trim()||(r.title+" "+r.text).toLowerCase().includes(replyQuery.trim().toLowerCase())));const recordRef=()=>({rowId:String(row?.original?.id??row?.id??""),row:row?.original??{}});async function openReplies(){if(repliesOpen){repliesOpen=false;return}const list=snippets;if(!list||!row)return;repliesOpen=true;replies=null;repliesError="";replyQuery="";naming=false;const forRow=row.id;try{const got=await list.list(ctrl?.props?.baseTableId,recordRef());if(row?.id===forRow)replies=Array.isArray(got)?got:[]}catch(e){repliesError=e instanceof Error?e.message:String(e);replies=[]}}function pickReply(reply){comment=comment.trim()?comment.replace(/\s+$/,"")+"\n\n"+reply.text:reply.text;if(reply.files?.length)commentFiles=[...commentFiles,...reply.files.filter(f=>!commentFiles.some(x=>x.id===f.id))];repliesOpen=false;void tick().then(()=>commentBox?.focus())}async function saveReply(){const keep=snippets?.save;const title2=replyName.trim();if(!keep||!title2||!comment.trim())return;try{await keep(ctrl?.props?.baseTableId,{title:title2,text:comment});toast.success(bm("record.replySaved"));naming=false;replyName="";replies=null;repliesOpen=false}catch(e){toast.error(bm("record.replyNotSaved",{error:e instanceof Error?e.message:String(e)}))}}$effect(()=>{void current;repliesOpen=false});function send(){if(!row||!canSend||!canComment||isDraft)return;addComment(ctrl,row.id,encodeMentions(comment,picked),{files:commentFiles,internal:internalNote});comment="";picked=[];commentFiles=[];internalNote=false;announce(bm("record.commentAddedSay"))}const fileSize=n=>n==null?"":n<1024?`${n} B`:n<1048576?`${Math.round(n/1024)} KB`:`${(n/1048576).toFixed(1)} MB`;let editingNote=$state(null);let editText=$state("");let editPicked=$state([]);let deletingNote=$state(null);let editBox=$state(null);let sendButton=$state(null);const unsaved=$derived(!!row&&(!!comment.trim()||editingNote!=null));$effect(()=>{const id=current;const drafts=commentDraftsOf(ctrl);const kept=drafts.get(id);comment=kept?.text??"";picked=kept?.picked??[];editingNote=null;deletingNote=null});$effect(()=>{const drafts=commentDraftsOf(ctrl);if(comment.trim())drafts.set(current,{text:comment,picked});else drafts.delete(current)});function closing(){if(comment.trim())toast.info(bm("record.commentKept"));onClose()}let escapeHeld=$state(false);let stepHeld=$state(false);$effect(()=>{void comment;void editText;escapeHeld=false;stepHeld=false});$effect(()=>{if(!unsaved)return;const onDown=e=>{if(!e.target?.classList?.contains("sv-modal__backdrop"))return;escapeHeld=true;announce(bm(editingNote!=null?"record.commentNotSaved":"record.commentNotSent"))};window.addEventListener("pointerdown",onDown,true);return()=>window.removeEventListener("pointerdown",onDown,true)});function escapeComment(e){const at2=e.target;if(!fieldsBox?.closest('[role="dialog"]')?.contains(at2))return;if(at2.getAttribute("aria-controls"))return;e.stopPropagation();if(deletingNote!=null)return keepNote();if(editingNote!=null&&at2.closest("form")?.contains(editBox))return cancelEdit();if(at2===commentBox)sendButton?.focus();escapeHeld=true;announce(bm(editingNote!=null?"record.commentNotSaved":"record.commentNotSent"))}let feedBox=$state(null);const focusNote=id=>void tick().then(()=>[...feedBox?.querySelectorAll("[data-note]")??[]].find(n=>n.dataset.note===id)?.querySelector("button")?.focus());function keepNote(){const id=deletingNote;deletingNote=null;if(id)focusNote(id)}const takeFocus=node=>node.focus();function startEdit(n){deletingNote=null;editingNote=n.id;editText=mentionText(n.text,id=>findFieldUser(id)?.name);editPicked=parseMentions(n.text).flatMap(p=>"mention"in p?[mentioned(p.mention,p.name)]:[]);void tick().then(()=>{editBox?.focus();editBox?.setSelectionRange(editText.length,editText.length)})}function saveEdit(){const id=editingNote;if(row&&id&&editText.trim()){editComment(ctrl,row.id,id,encodeMentions(editText,editPicked));announce(bm("record.commentSavedSay"))}editingNote=null;if(id)focusNote(id)}function cancelEdit(){const id=editingNote;editingNote=null;if(id)focusNote(id)}const mentioned=(id,name)=>findFieldUser(id)??{id,name:name||bm("record.someone")};
|
|
2
|
+
import{recordActionsFor}from"./record-actions";import{commentSnippets}from"./comment-snippets.svelte";import{onDestroy,onMount,tick,untrack}from"svelte";import{commentDraftsOf,getRecordRequest,holdForRecordEditor}from"./editor-request.svelte";import{SvModal,announce,toast}from"@svgrid/grid";import FieldInput from"./FieldInput.svelte";import{fieldPropsOf,getFieldType,originalColumn,ruleFieldNames}from"./registry.svelte";import{protectionText}from"./field-access.svelte";import{isReadOnlyGrid}from"./base-share";import{canCommentIn,canDeleteRecord}from"./base-permissions";import{askDeleteRecord}from"./record-delete.svelte";import{cellText,dataRows,fieldColumns,leafFilter,primaryIdOf}from"./grid-access";import{recordWalkOf}from"./record-walk";import{addComment,commentStoreTakes,commentVotes,commentsOf,commentsTakeVotes,deleteComment,editComment,historyOf,historyState,loadHistory,markSeen,mayVoteComment,myCommentVote,ownsComment,timeAgo,unseenOf,voteComment}from"./activity.svelte";import{uploadAttachment}from"./attachments";import{findFieldUser}from"./sources.svelte";import{encodeMentions,mentionText,parseMentions}from"./mentions";import MentionInput from"./MentionInput.svelte";import{dictationSupported,dictate,withSaid}from"./dictation.svelte";import UserFace from"./UserFace.svelte";import{recordProposalsFor}from"../review/card-marks.svelte";import{bm,bmCount}from"./messages.svelte";let{ctrl,rowId,editPrimary=false,focus,onClose}=$props();let current=$state(rowId);let open=$state(true);let editing=$state(null);let showHidden=$state(false);let comment=$state("");let picked=$state([]);const rows=$derived(ctrl.allRows??[]);let lastAt=-1;function rowIndexOf(list,id){if(id==null)return-1;for(const near of[lastAt,untrack(()=>ctrl.activeCell?.rowIndex??-1)]){if(near<0)continue;for(let d=0;d<=200;d++){if(list[near+d]?.id===id)return lastAt=near+d;if(d&&near-d>=0&&list[near-d]?.id===id)return lastAt=near-d}}return lastAt=list.findIndex(r=>r.id===id)}const index=$derived(rowIndexOf(rows,current));const row=$derived(index>=0?rows[index]:null);const isDraft=$derived(!!ctrl.props?.baseIsDraft?.(current));let lastIndex=0;const at=$derived.by(()=>{if(index>=0)lastIndex=index;return lastIndex});const walk=$derived(recordWalkOf(ctrl));const model=$derived(ctrl.props?.rowModel);const grouped=$derived((ctrl.groupingColumns??[]).length>0);const notRead=r=>String(r.id).startsWith("sv-ph:");function isRecord(r){const kind=r.original?.__group?.kind;return kind?kind==="leaf":r.__treeRow||!(typeof r.getCanExpand==="function"&&r.getCanExpand())}function rowFrom(from,by){for(let i=from+by;i>=0&&i<rows.length;i+=by){const r=rows[i];if(notRead(r)||isRecord(r))return i}return-1}function rowBeside(by){const seen=at;return rowFrom(index>=0?index:by>0?seen-1:seen,by)}let located=$state(0);const walkPlace=$derived(walk&&!isDraft?(void located,walk.place(current)):null);let lastPlace=-1;const walkAt=$derived.by(()=>{if(walkPlace!=null)lastPlace=walkPlace;return lastPlace});const walkFrom=by=>walkPlace!=null?walkAt:by>0?walkAt-1:walkAt;const canPrev=$derived(walk?walkAt>=0&&walk.has(walkFrom(-1),-1):rowBeside(-1)>=0);const canNext=$derived(walk?walkAt>=0&&walk.has(walkFrom(1),1):rowBeside(1)>=0);const records=$derived(!model&&grouped?dataRows(ctrl):null);const total=$derived(walk?walk.total():model?.getState?model.recordCount?.()??model.getState().rowCount??rows.length:(records??rows).length);const locale=$derived(ctrl.props?.localization?.locale);const place=$derived.by(()=>{if(isDraft)return null;if(walk)return walkPlace;if(index<0)return null;if(model)return grouped||model.isPinned?.(current)?null:index-Math.max(0,rows.length-total);return records?records.findIndex(r=>r.id===current):index});const positionText=$derived.by(()=>{if(isDraft)return bm("record.newRecord");if(!walk&&index<0)return bmCount("record.notInView",total,{count:total.toLocaleString(locale)});if(place==null)return bmCount("viewbar.records",total);return bm("record.position",{index:(place+1).toLocaleString(locale),total:total.toLocaleString(locale)})});const filteredOut=$derived.by(()=>{if(!row)return false;const keep=leafFilter(ctrl);return!!keep&&!keep(row)});const columns=$derived((ctrl.allColumns??[]).filter(c=>!c.id.startsWith("__")&&(c.columnDef.field!=null||c.columnDef.fieldFn!=null)));const hidden=$derived.by(()=>{const shownIds=new Set(columns.map(c=>c.id));return fieldColumns(ctrl).filter(c=>!shownIds.has(c.id)).map(c=>({id:c.id,columnDef:c.def}))});function valueOf(c){if(!row)return void 0;const base=c.columnDef.fieldFn?c.columnDef.fieldFn(row.original):row.original?.[c.columnDef.field];return ctrl.getCellDisplayValue(row.id,c.id,columns.includes(c)?row.getCellValueByColumnId(c.id):base)}const asField=c=>({id:c.id,field:String(c.columnDef.field??c.id),header:label(c),fieldType:c.columnDef.fieldType,def:c.columnDef,visible:true});const primaryId=$derived(primaryIdOf(ctrl));const primary=$derived(columns.find(c=>c.id===primaryId)??columns.find(c=>c.columnDef.fieldType==="text"||!c.columnDef.fieldType&&c.columnDef.editorType==null)??columns[0]);const title=$derived(row&&primary?cellText(asField(primary),valueOf(primary),row)||bm("record.untitled"):bm("record.record"));function label(c){return typeof c.columnDef.header==="string"?c.columnDef.header:c.id}const protectionOf=c=>c.columnDef.fieldType?protectionText(originalColumn(c.columnDef),fieldPropsOf(originalColumn(c.columnDef)),ruleFieldNames(c.columnDef)):null;const iconOf=c=>c.columnDef.fieldType?getFieldType(c.columnDef.fieldType)?.icon:void 0;function editable(c){if(!row||!ctrl.editingEnabled)return false;const ci=ctrl.allColumns.findIndex(x=>x.id===c.id);if(ci<0)return false;return ctrl.isCellEditableAt?!!ctrl.isCellEditableAt(index,ci):c.columnDef.editable!==false}const editorOpen=$derived(editing!=null);$effect(()=>{if(editorOpen)return untrack(holdForRecordEditor)});onMount(()=>{if(editPrimary&&primary&&editable(primary))editing=primary.id});let settled=$state(false);const settling=setTimeout(()=>settled=true,400);onDestroy(()=>{clearTimeout(settling);walk?.stop?.()});let locating=null;$effect(()=>{const w=walk;const r=row;if(!w?.locate||!r||isDraft||walkPlace!=null||locating===r.id)return;locating=r.id;untrack(()=>void w.locate(r.id,r.original).finally(()=>located+=1))});let commentBox=$state(null);const commentFocusFor=r=>r?.focus==="comment"&&r.ctrl===ctrl;const initialFocus=()=>focus==="comment"||commentFocusFor(getRecordRequest())?commentBox:null;$effect(()=>{const r=getRecordRequest();if(!commentFocusFor(r))return;untrack(()=>{if(r.rowId!==current)current=r.rowId;queueMicrotask(()=>commentBox?.focus())})});let listening=$state(null);const speakable=c=>dictationSupported()&&(c.columnDef.fieldType==="text"||c.columnDef.fieldType==="longText");async function speakInto(c){if(listening)return;listening=c.id;try{const said=await dictate();if(said)commit(c,withSaid(row?.getCellValueByColumnId?.(c.id),said,c.columnDef.fieldType==="longText"))}finally{listening=null}}async function speakComment(){if(listening)return;listening=":comment";try{const said=await dictate();if(said)comment=withSaid(comment,said,false)}finally{listening=null}}function commit(c,v){editing=null;if(!row||v===void 0)return;const none=x=>x==null||x===""||Array.isArray(x)&&!x.length;if(none(v)&&none(row.getCellValueByColumnId?.(c.id)))return;const at2=rowIndexOf(ctrl.allRows,current);if(at2<0||!ctrl.startEditing(at2,c.id))return;ctrl.updateEditingCellValue(v);ctrl.saveEditingCell()}let fieldsBox=$state(null);const focusField=id=>[...fieldsBox?.querySelectorAll("[data-frv-field]")??[]].find(el=>el.dataset.frvField===id)?.querySelector(".sv-frv-open")?.focus();function stopEditing(c){editing=null;setTimeout(()=>{const now=document.activeElement;if(editing==null&&(!now||now===document.body||now.getAttribute("role")==="dialog"))focusField(c.id)},0)}const typedInto=c=>["text","number","textarea","fieldNumber","fieldTime",void 0].includes(c.columnDef.editorType);function escapeBox(e){if(e.key!=="Escape"||e.isComposing)return;if((unsaved||deletingNote!=null)&&editing==null)return escapeComment(e);const c=editing!=null?columns.find(x=>x.id===editing):void 0;if(!c||!(typedInto(c)||c.columnDef.editorType==="fieldRating"))return;e.stopPropagation();stopEditing(c)}function editBeside(c,dir){const at2=columns.findIndex(x=>x.id===c.id);for(let i=at2+dir;i>=0&&i<columns.length;i+=dir){const next=columns[i];if(!editable(next)||next.columnDef.editorType==="checkbox")continue;if(typedInto(next))editing=next.id;else{editing=null;void tick().then(()=>focusField(next.id))}return}}let awaited=$state(null);let awaitedRow=$state(null);let stepping=false;let pressed=0;function arrived(){stepping=false;if(!pressed)return;const by=pressed>0?1:-1;pressed-=by;queueMicrotask(()=>void go(by))}$effect(()=>{const id=awaited;if(id!=null&&rowIndexOf(rows,id)>=0)untrack(()=>{current=id;awaited=null;arrived()})});$effect(()=>{const at2=awaitedRow;const r=at2==null?void 0:rows[at2];if(r&&!notRead(r))untrack(()=>{awaitedRow=null;lastAt=at2;if(isRecord(r))current=r.id;arrived()})});let swipeAt=null;function swipeStart(e){const t=e.touches[0];const from=e.target;const busy=!!from?.closest?.('input, textarea, select, [contenteditable="true"], .sv-frv-files, [data-no-swipe]');swipeAt=e.touches.length===1&&t&&!busy?{x:t.clientX,y:t.clientY,t:Date.now()}:null}function swipeEnd(e){const s0=swipeAt;swipeAt=null;const t=e.changedTouches[0];if(!s0||!t||editing!=null)return;const dx=t.clientX-s0.x;const dy=t.clientY-s0.y;if(Math.abs(dx)<70||Math.abs(dx)<Math.abs(dy)*1.8||Date.now()-s0.t>700)return;if(dx<0&&canNext)void go(1);else if(dx>0&&canPrev)void go(-1)}function keepInSight(e){const el=e.target;if(!el?.matches?.('input, textarea, [contenteditable="true"]')||typeof window==="undefined"||window.innerWidth>600)return;setTimeout(()=>el.scrollIntoView?.({block:"center",behavior:"smooth"}),320)}async function go(by){if(stepping){pressed+=by;return}if(editingNote!=null){stepHeld=true;announce(bm("record.commentHoldsStep"));editBox?.focus();return}editing=null;if(walk){stepping=true;const id=await walk.step(walkFrom(by),by);if(id==null){stepping=false;pressed=0;return}awaited=id;setTimeout(()=>{if(awaited!==id)return;awaited=null;stepping=false;pressed=0},3e3);return}const to=rowBeside(by);if(to<0)return;const next=rows[to];if(!notRead(next)){lastAt=to;current=next.id;return}stepping=true;awaitedRow=to;ctrl.buildApi?.().scrollToRow?.(to)}const allCols=$derived([...columns,...hidden]);const feed=$derived.by(()=>{if(!row)return[];const edits=historyOf(ctrl,row.id).map((ch,i)=>{if(ch.added)return{key:`a${ch.at}-${i}`,at:ch.at,by:ch.by,remote:true,kind:"added",field:"",text:""};const c=allCols.find(x=>x.id===ch.columnId);const show=v=>c?cellText(asField(c),v,row):String(v??"");return{key:`e${ch.at}${ch.columnId}-${i}`,at:ch.at,by:ch.by,automation:ch.automation,via:ch.via,through:ch.through,remote:ch.remote,undone:ch.undone,redone:ch.redone,kind:"edit",field:c?label(c):ch.columnId,text:show(ch.value),..."from"in ch&&show(ch.from)?{from:show(ch.from)}:{}}});const notes=commentsOf(ctrl,row.id).map(n=>({key:n.id,at:n.at,by:n.by,kind:"comment",field:"",text:n.text,parts:parseMentions(n.text),note:n}));return[...edits,...notes].sort((a,b)=>a.at-b.at)});const person=item=>item.by?findFieldUser(item.by)?.name??bm("record.someone"):item.remote?bm("record.someoneElse"):bm("record.you");const who=item=>item.automation?bm("record.byAutomation",{name:item.automation}):item.via?bm("record.acceptedBy",{source:item.via,person:person(item)}):item.through?bm("record.through",{person:person(item),source:item.through}):person(item);const shownId=$derived(row?.id);$effect(()=>{const id=shownId;if(id!=null)untrack(()=>loadHistory(ctrl,id))});const history=$derived(row?historyState(ctrl,row.id):{loading:false});$effect(()=>{const id=row?.id;if(id!=null&&unseenOf(ctrl,id))untrack(()=>markSeen(ctrl,id))});const proposals=$derived(row?recordProposalsFor(ctrl.props?.getRowId,row.original,row.id):null);const proposalOf=c=>proposals?.list.find(p=>p.field===String(c.columnDef.field??c.id));const proposedText=(c,p)=>cellText(asField(c),p.after,row)||proposals?.messages.empty||"";let deciding=$state(false);async function decide(ids,how){if(!proposals||deciding||!ids.length)return;deciding=true;try{await(how==="accept"?proposals.accept(ids):proposals.reject(ids))}finally{deciding=false}}const readOnly=$derived(isReadOnlyGrid(ctrl));const canComment=$derived(canCommentIn(ctrl));const takesFiles=$derived(commentStoreTakes("files"));const takesInternal=$derived(commentStoreTakes("internal"));let commentFiles=$state([]);let uploading=$state(0);let internalNote=$state(false);let fileInput=$state(null);const canSend=$derived((!!comment.trim()||commentFiles.length>0)&&uploading===0);async function attach(list){if(!list||!row)return;const forRow=row.id;for(const file of Array.from(list)){uploading+=1;try{const done=await uploadAttachment(file,{},{row:row?.original,columnId:"",signal:new AbortController().signal,onProgress:()=>{}});if(row?.id===forRow)commentFiles=[...commentFiles,done]}catch(e){toast.error(bm("record.commentUploadFailed",{name:file.name,error:e instanceof Error?e.message:String(e)}))}finally{uploading-=1}}if(fileInput)fileInput.value=""}const snippets=$derived(commentSnippets());let repliesOpen=$state(false);let replies=$state(null);let repliesError=$state("");let replyQuery=$state("");let replyName=$state("");let naming=$state(false);const shownReplies=$derived((replies??[]).filter(r=>!replyQuery.trim()||(r.title+" "+r.text).toLowerCase().includes(replyQuery.trim().toLowerCase())));const recordRef=()=>({rowId:String(row?.original?.id??row?.id??""),row:row?.original??{}});async function openReplies(){if(repliesOpen){repliesOpen=false;return}const list=snippets;if(!list||!row)return;repliesOpen=true;replies=null;repliesError="";replyQuery="";naming=false;const forRow=row.id;try{const got=await list.list(ctrl?.props?.baseTableId,recordRef());if(row?.id===forRow)replies=Array.isArray(got)?got:[]}catch(e){repliesError=e instanceof Error?e.message:String(e);replies=[]}}function pickReply(reply){comment=comment.trim()?comment.replace(/\s+$/,"")+"\n\n"+reply.text:reply.text;if(reply.files?.length)commentFiles=[...commentFiles,...reply.files.filter(f=>!commentFiles.some(x=>x.id===f.id))];repliesOpen=false;void tick().then(()=>commentBox?.focus())}async function saveReply(){const keep=snippets?.save;const title2=replyName.trim();if(!keep||!title2||!comment.trim())return;try{await keep(ctrl?.props?.baseTableId,{title:title2,text:comment});toast.success(bm("record.replySaved"));naming=false;replyName="";replies=null;repliesOpen=false}catch(e){toast.error(bm("record.replyNotSaved",{error:e instanceof Error?e.message:String(e)}))}}$effect(()=>{void current;repliesOpen=false});function send(){if(!row||!canSend||!canComment||isDraft)return;addComment(ctrl,row.id,encodeMentions(comment,picked),{files:commentFiles,internal:internalNote});comment="";picked=[];commentFiles=[];internalNote=false;announce(bm("record.commentAddedSay"))}const fileSize=n=>n==null?"":n<1024?`${n} B`:n<1048576?`${Math.round(n/1024)} KB`:`${(n/1048576).toFixed(1)} MB`;let editingNote=$state(null);let editText=$state("");let editPicked=$state([]);let deletingNote=$state(null);let editBox=$state(null);let sendButton=$state(null);const unsaved=$derived(!!row&&(!!comment.trim()||editingNote!=null));$effect(()=>{const id=current;const drafts=commentDraftsOf(ctrl);const kept=drafts.get(id);comment=kept?.text??"";picked=kept?.picked??[];editingNote=null;deletingNote=null});$effect(()=>{const drafts=commentDraftsOf(ctrl);if(comment.trim())drafts.set(current,{text:comment,picked});else drafts.delete(current)});function closing(){if(comment.trim())toast.info(bm("record.commentKept"));onClose()}let escapeHeld=$state(false);let stepHeld=$state(false);$effect(()=>{void comment;void editText;escapeHeld=false;stepHeld=false});$effect(()=>{if(!unsaved)return;const onDown=e=>{if(!e.target?.classList?.contains("sv-modal__backdrop"))return;escapeHeld=true;announce(bm(editingNote!=null?"record.commentNotSaved":"record.commentNotSent"))};window.addEventListener("pointerdown",onDown,true);return()=>window.removeEventListener("pointerdown",onDown,true)});function escapeComment(e){const at2=e.target;if(!fieldsBox?.closest('[role="dialog"]')?.contains(at2))return;if(at2.getAttribute("aria-controls"))return;e.stopPropagation();if(deletingNote!=null)return keepNote();if(editingNote!=null&&at2.closest("form")?.contains(editBox))return cancelEdit();if(at2===commentBox)sendButton?.focus();escapeHeld=true;announce(bm(editingNote!=null?"record.commentNotSaved":"record.commentNotSent"))}let feedBox=$state(null);const focusNote=id=>void tick().then(()=>[...feedBox?.querySelectorAll("[data-note]")??[]].find(n=>n.dataset.note===id)?.querySelector("button")?.focus());function keepNote(){const id=deletingNote;deletingNote=null;if(id)focusNote(id)}const takeFocus=node=>node.focus();function startEdit(n){deletingNote=null;editingNote=n.id;editText=mentionText(n.text,id=>findFieldUser(id)?.name);editPicked=parseMentions(n.text).flatMap(p=>"mention"in p?[mentioned(p.mention,p.name)]:[]);void tick().then(()=>{editBox?.focus();editBox?.setSelectionRange(editText.length,editText.length)})}function saveEdit(){const id=editingNote;if(row&&id&&editText.trim()){editComment(ctrl,row.id,id,encodeMentions(editText,editPicked));announce(bm("record.commentSavedSay"))}editingNote=null;if(id)focusNote(id)}function cancelEdit(){const id=editingNote;editingNote=null;if(id)focusNote(id)}const mentioned=(id,name)=>findFieldUser(id)??{id,name:name||bm("record.someone")};function voteTitle(dir,ids){if(!ids.length)return bm(dir==="up"?"record.voteUp":"record.voteDown");const names=ids.map(id=>findFieldUser(id)?.name??bm("record.someone"));const list=names.join(", ");return bm(dir==="up"?"record.votedUpBy":"record.votedDownBy",{names:list})}
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
{#snippet field(c: Col, canEdit: boolean)}
|
|
@@ -127,18 +127,36 @@ import{recordActionsFor}from"./record-actions";import{commentSnippets}from"./com
|
|
|
127
127
|
</ul>
|
|
128
128
|
{/if}
|
|
129
129
|
</div>
|
|
130
|
-
{#if item.note
|
|
130
|
+
{#if item.note}
|
|
131
131
|
{@const note = item.note}
|
|
132
|
-
{
|
|
132
|
+
{@const votes = commentVotes(note)}
|
|
133
|
+
{@const mine = myCommentVote(note)}
|
|
134
|
+
{@const voting = canComment && mayVoteComment(note)}
|
|
135
|
+
{@const showVotes = commentsTakeVotes() && (voting || votes.up.length > 0 || votes.down.length > 0)}
|
|
136
|
+
{@const owns = canComment && (ownsComment(note, 'update') || ownsComment(note, 'remove'))}
|
|
137
|
+
{#if canComment && deletingNote === note.id}
|
|
133
138
|
<div class="sv-frv-note-acts" role="group" aria-label={bm('record.deleteCommentAsk')}>
|
|
134
139
|
<span>{bm('record.deleteCommentAsk')}</span>
|
|
135
140
|
<button type="button" class="sv-frv-link" onclick={() => { if (row) deleteComment(ctrl, row.id, note.id); deletingNote = null; announce(bm('record.commentDeletedSay')) }}>{bm('record.deleteComment')}</button>
|
|
136
141
|
<button type="button" class="sv-frv-link" use:takeFocus onclick={keepNote}>{bm('record.cancelComment')}</button>
|
|
137
142
|
</div>
|
|
138
|
-
{:else if
|
|
143
|
+
{:else if showVotes || owns}
|
|
139
144
|
<div class="sv-frv-note-acts" data-note={note.id}>
|
|
140
|
-
{#if
|
|
141
|
-
|
|
145
|
+
{#if showVotes}
|
|
146
|
+
|
|
147
|
+
<span class="sv-frv-votes" role="group" aria-label={bm('record.commentVotes')}>
|
|
148
|
+
<button type="button" class="sv-frv-vote" class:is-mine={mine === 'up'} aria-pressed={mine === 'up'} aria-label={bm('record.voteUpCount', { count: votes.up.length })} title={voteTitle('up', votes.up)} disabled={!voting} onclick={() => { if (row) voteComment(ctrl, row.id, note.id, 'up') }}>
|
|
149
|
+
<svg viewBox="0 0 24 24" width="13" height="13" aria-hidden="true"><path d="M7 10v11H3V10h4zm2 11h8.3a2 2 0 0 0 2-1.6l1.4-7A2 2 0 0 0 18.7 10H14V5.5A2.5 2.5 0 0 0 11.5 3L9 10v11z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
|
|
150
|
+
<span>{votes.up.length}</span>
|
|
151
|
+
</button>
|
|
152
|
+
<button type="button" class="sv-frv-vote is-down" class:is-mine={mine === 'down'} aria-pressed={mine === 'down'} aria-label={bm('record.voteDownCount', { count: votes.down.length })} title={voteTitle('down', votes.down)} disabled={!voting} onclick={() => { if (row) voteComment(ctrl, row.id, note.id, 'down') }}>
|
|
153
|
+
<svg viewBox="0 0 24 24" width="13" height="13" aria-hidden="true"><path d="M17 14V3h4v11h-4zM15 3H6.7a2 2 0 0 0-2 1.6l-1.4 7A2 2 0 0 0 5.3 14H10v4.5a2.5 2.5 0 0 0 2.5 2.5L15 14V3z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
|
|
154
|
+
<span>{votes.down.length}</span>
|
|
155
|
+
</button>
|
|
156
|
+
</span>
|
|
157
|
+
{/if}
|
|
158
|
+
{#if owns && ownsComment(note, 'update')}<button type="button" class="sv-frv-link" onclick={() => startEdit(note)}>{bm('record.editComment')}</button>{/if}
|
|
159
|
+
{#if owns && ownsComment(note, 'remove')}<button type="button" class="sv-frv-link" onclick={() => { editingNote = null; deletingNote = note.id }}>{bm('record.deleteComment')}</button>{/if}
|
|
142
160
|
</div>
|
|
143
161
|
{/if}
|
|
144
162
|
{/if}
|
|
@@ -241,7 +259,7 @@ import{recordActionsFor}from"./record-actions";import{commentSnippets}from"./com
|
|
|
241
259
|
<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
|
|
242
260
|
</button>
|
|
243
261
|
<span class="sv-frv-pos">{positionText}</span>
|
|
244
|
-
{#if row && !readOnly && ctrl.editingEnabled &&
|
|
262
|
+
{#if row && !readOnly && ctrl.editingEnabled && canDeleteRecord(ctrl, row) && !row.__treeRow}
|
|
245
263
|
<button
|
|
246
264
|
type="button"
|
|
247
265
|
class="sv-frv-btn is-danger"
|
|
@@ -271,5 +289,5 @@ import{recordActionsFor}from"./record-actions";import{commentSnippets}from"./com
|
|
|
271
289
|
</SvModal>
|
|
272
290
|
|
|
273
291
|
<style>
|
|
274
|
-
.sv-frv-proposals{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 12px;padding:8px 12px;border-radius:var(--sg-radius, 6px);font-size:13px;background:color-mix(in srgb,var(--sg-accent, #2563eb) 8%,var(--sg-bg, #fff));border:1px solid color-mix(in srgb,var(--sg-accent, #2563eb) 30%,var(--sg-border, #e2e8f0))}.sv-frv-proposal{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;margin-top:6px;padding:6px 8px;font-size:13px;border-inline-start:3px solid var(--sg-accent, #2563eb);border-radius:0 var(--sg-radius, 6px) var(--sg-radius, 6px) 0;background:color-mix(in srgb,var(--sg-accent, #2563eb) 6%,var(--sg-bg, #fff))}.sv-frv-proposal-by{color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-filtered{display:flex;align-items:center;gap:6px;margin:0 0 12px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-frv-filtered svg{flex:none}.sv-frv-proposal-value{font-weight:600;overflow-wrap:anywhere}.sv-frv-proposal-acts{display:inline-flex;gap:6px;margin-inline-start:auto}.sv-frv-proposal-acts .sv-frv-btn{height:26px;padding:0 10px}.sv-frv-btn.is-accept{background:var(--sg-accent, #2563eb);border-color:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}.sv-frv-proposal-why{flex-basis:100%;color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:20px;align-items:start}.sv-frv-fields{display:flex;flex-direction:column;gap:14px;min-width:0}.sv-frv-field{display:flex;flex-direction:column;gap:6px}.sv-frv-label{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--sg-muted, #64748b)}.sv-frv-mic{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;margin:-8px -6px -8px auto;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sg-accent, #2563eb);cursor:pointer}.sv-frv-mic:hover:not(:disabled){background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-frv-mic:disabled:not(.is-on){opacity:.4;cursor:default}.sv-frv-mic.is-on,.sv-frv-mic-comment.is-on{color:var(--sg-danger, #dc2626);animation:sv-frv-listen 1s ease-in-out infinite}.sv-frv-mic-comment{display:inline-flex;align-items:center;gap:4px}@keyframes sv-frv-listen{50%{opacity:.45}}@media(prefers-reduced-motion:reduce){.sv-frv-mic.is-on,.sv-frv-mic-comment.is-on{animation:none}}.sv-frv-ro{font-weight:400;font-size:11px;opacity:.8}.sv-frv-hidden-toggle{align-self:flex-start;border:0;padding:2px 0;background:none;font:inherit;font-size:13px;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}.sv-frv-activity{position:sticky;top:0;display:flex;flex-direction:column;gap:8px;max-height:70vh;padding-inline-start:16px;border-inline-start:1px solid var(--sg-border, #e2e8f0)}.sv-frv-activity-title{margin:0;font-size:13px;font-weight:600}.sv-frv-feed{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:10px;overflow:auto;min-height:60px}.sv-frv-item{font-size:12px}.sv-frv-item-head{color:var(--sg-muted, #64748b)}.sv-frv-item-head strong{color:var(--sg-fg, #0f172a);font-weight:600}.sv-frv-from{color:var(--sg-muted, #64748b);text-decoration:line-through}.sv-frv-arrow{margin:0 5px;color:var(--sg-muted, #64748b)}.sv-frv-when{margin-inline-start:6px;color:var(--sg-fg, #0f172a)}.sv-frv-note-acts{display:flex;align-items:center;justify-content:flex-end;gap:10px;margin-top:4px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-frv-link{padding:0;border:0;background:none;font:inherit;font-size:12px;color:var(--sg-muted, #64748b);cursor:pointer}.sv-frv-link:hover{color:var(--sg-fg, #0f172a);text-decoration:underline}.sv-frv-link:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-frv-item-body{margin-top:2px;white-space:pre-wrap;word-break:break-word}.sv-frv-item.is-comment .sv-frv-item-body{padding:6px 8px;border-radius:8px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 5%,transparent)}.sv-frv-none{color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-comment{display:grid;gap:6px}.sv-frv-held{margin:0;font-size:12px;color:var(--sg-fg, #0f172a)}.sv-frv-mention{display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 2px;border-radius:999px;vertical-align:baseline;font-weight:600;color:var(--sg-accent, #2563eb);background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-frv-comment .sv-frv-btn{justify-self:end}.sv-frv-send{display:flex;align-items:center;justify-content:flex-end;gap:12px;flex-wrap:wrap}.sv-frv-attach{display:inline-flex;align-items:center;gap:4px;margin-inline-end:auto}.sv-frv-internal{display:inline-flex;align-items:center;gap:4px;font-size:12px;color:var(--sg-muted, #64748b);cursor:pointer}.sv-frv-files{list-style:none;margin:6px 0 0;padding:0;display:flex;flex-direction:column;gap:3px}.sv-frv-replies-open{display:inline-flex;align-items:center;gap:4px}.sv-frv-replies{display:flex;flex-direction:column;gap:6px;padding:8px;border:1px solid var(--sg-border, #e2e8f0);border-radius:8px;background:var(--sg-bg, #fff)}.sv-frv-replies-search,.sv-frv-replies-save input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid var(--sg-border, #e2e8f0);border-radius:6px;background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a);min-width:0}.sv-frv-replies-list{list-style:none;margin:0;padding:0;max-height:220px;overflow:auto;display:flex;flex-direction:column;gap:2px}.sv-frv-reply{display:flex;flex-direction:column;gap:2px;width:100%;text-align:start;padding:6px 8px;border:0;border-radius:6px;background:none;font:inherit;font-size:13px;color:inherit;cursor:pointer}.sv-frv-reply:hover,.sv-frv-reply:focus-visible{background:var(--sg-hover, #f1f5f9)}.sv-frv-reply span{color:var(--sg-muted, #64748b);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-frv-replies-save{display:flex;gap:6px}.sv-frv-replies-save input{flex:1}.sv-frv-files li{display:flex;align-items:baseline;gap:6px;min-width:0;overflow-wrap:anywhere}.sv-frv-files a{color:var(--sg-accent, #2563eb)}.sv-frv-files.is-draft{margin:0;font-size:12px}.sv-frv-internal-tag{margin-inline-start:6px;padding:0 6px;border-radius:999px;font-size:11px;font-weight:600;color:#92400e;background:#fef3c7}.sv-frv-item.is-comment.is-internal .sv-frv-item-body{background:color-mix(in srgb,#f59e0b 12%,transparent)}.sv-frv-gone{color:var(--sg-muted, #64748b)}.sv-frv-footer{display:flex;align-items:center;gap:6px;width:100%}.sv-frv-pos{flex:1;font-size:13px;color:var(--sg-muted, #64748b)}.sv-frv-btn{display:inline-flex;align-items:center;justify-content:center;height:32px;min-width:32px;padding:0 12px;font:inherit;font-size:13px;cursor:pointer;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px);background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a)}.sv-frv-btn:disabled{opacity:.4;cursor:default}.sv-frv-btn.is-primary{background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);border-color:var(--sg-fg, #0f172a)}.sv-frv-btn.is-danger{color:var(--sg-danger, #b91c1c)}@media(max-width:760px){.sv-frv-layout{grid-template-columns:minmax(0,1fr)}.sv-frv-activity{position:static;padding-inline-start:0;border-inline-start:0;border-top:1px solid var(--sg-border, #e2e8f0);padding-top:12px}}@media(max-width:600px){:global(.sv-modal:has(.sv-frv-layout)){width:100vw!important;max-width:100vw;height:100dvh;max-height:100dvh;border-radius:0}}.sv-frv-apps{display:flex;flex-wrap:wrap;gap:14px;justify-content:flex-end;margin:0 0 8px}.sv-frv-app{display:inline-flex;align-items:center;gap:5px}
|
|
292
|
+
.sv-frv-proposals{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 12px;padding:8px 12px;border-radius:var(--sg-radius, 6px);font-size:13px;background:color-mix(in srgb,var(--sg-accent, #2563eb) 8%,var(--sg-bg, #fff));border:1px solid color-mix(in srgb,var(--sg-accent, #2563eb) 30%,var(--sg-border, #e2e8f0))}.sv-frv-proposal{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;margin-top:6px;padding:6px 8px;font-size:13px;border-inline-start:3px solid var(--sg-accent, #2563eb);border-radius:0 var(--sg-radius, 6px) var(--sg-radius, 6px) 0;background:color-mix(in srgb,var(--sg-accent, #2563eb) 6%,var(--sg-bg, #fff))}.sv-frv-proposal-by{color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-filtered{display:flex;align-items:center;gap:6px;margin:0 0 12px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-frv-filtered svg{flex:none}.sv-frv-proposal-value{font-weight:600;overflow-wrap:anywhere}.sv-frv-proposal-acts{display:inline-flex;gap:6px;margin-inline-start:auto}.sv-frv-proposal-acts .sv-frv-btn{height:26px;padding:0 10px}.sv-frv-btn.is-accept{background:var(--sg-accent, #2563eb);border-color:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}.sv-frv-proposal-why{flex-basis:100%;color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:20px;align-items:start}.sv-frv-fields{display:flex;flex-direction:column;gap:14px;min-width:0}.sv-frv-field{display:flex;flex-direction:column;gap:6px}.sv-frv-label{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--sg-muted, #64748b)}.sv-frv-mic{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;margin:-8px -6px -8px auto;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sg-accent, #2563eb);cursor:pointer}.sv-frv-mic:hover:not(:disabled){background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-frv-mic:disabled:not(.is-on){opacity:.4;cursor:default}.sv-frv-mic.is-on,.sv-frv-mic-comment.is-on{color:var(--sg-danger, #dc2626);animation:sv-frv-listen 1s ease-in-out infinite}.sv-frv-mic-comment{display:inline-flex;align-items:center;gap:4px}@keyframes sv-frv-listen{50%{opacity:.45}}@media(prefers-reduced-motion:reduce){.sv-frv-mic.is-on,.sv-frv-mic-comment.is-on{animation:none}}.sv-frv-ro{font-weight:400;font-size:11px;opacity:.8}.sv-frv-hidden-toggle{align-self:flex-start;border:0;padding:2px 0;background:none;font:inherit;font-size:13px;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}.sv-frv-activity{position:sticky;top:0;display:flex;flex-direction:column;gap:8px;max-height:70vh;padding-inline-start:16px;border-inline-start:1px solid var(--sg-border, #e2e8f0)}.sv-frv-activity-title{margin:0;font-size:13px;font-weight:600}.sv-frv-feed{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:10px;overflow:auto;min-height:60px}.sv-frv-item{font-size:12px}.sv-frv-item-head{color:var(--sg-muted, #64748b)}.sv-frv-item-head strong{color:var(--sg-fg, #0f172a);font-weight:600}.sv-frv-from{color:var(--sg-muted, #64748b);text-decoration:line-through}.sv-frv-arrow{margin:0 5px;color:var(--sg-muted, #64748b)}.sv-frv-when{margin-inline-start:6px;color:var(--sg-fg, #0f172a)}.sv-frv-note-acts{display:flex;align-items:center;justify-content:flex-end;gap:10px;margin-top:4px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-frv-link{padding:0;border:0;background:none;font:inherit;font-size:12px;color:var(--sg-muted, #64748b);cursor:pointer}.sv-frv-link:hover{color:var(--sg-fg, #0f172a);text-decoration:underline}.sv-frv-votes{display:inline-flex;gap:4px;margin-right:auto}.sv-frv-vote{display:inline-flex;align-items:center;gap:4px;min-height:24px;padding:2px 8px;border:1px solid var(--sg-border, #e2e8f0);border-radius:999px;background:var(--sg-bg, #fff);font:inherit;font-size:12px;color:var(--sg-muted, #64748b);cursor:pointer}.sv-frv-vote:hover:not(:disabled){color:var(--sg-fg, #0f172a);border-color:color-mix(in srgb,var(--sg-fg, #0f172a) 30%,transparent)}.sv-frv-vote:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-frv-vote:disabled{cursor:default}.sv-frv-vote.is-mine{color:var(--sg-accent, #2563eb);border-color:var(--sg-accent, #2563eb);background:color-mix(in srgb,var(--sg-accent, #2563eb) 10%,transparent)}.sv-frv-vote.is-down.is-mine{color:#b42318;border-color:#b42318;background:color-mix(in srgb,#b42318 10%,transparent)}.sv-frv-link:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-frv-item-body{margin-top:2px;white-space:pre-wrap;word-break:break-word}.sv-frv-item.is-comment .sv-frv-item-body{padding:6px 8px;border-radius:8px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 5%,transparent)}.sv-frv-none{color:var(--sg-muted, #64748b);font-size:12px}.sv-frv-comment{display:grid;gap:6px}.sv-frv-held{margin:0;font-size:12px;color:var(--sg-fg, #0f172a)}.sv-frv-mention{display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 2px;border-radius:999px;vertical-align:baseline;font-weight:600;color:var(--sg-accent, #2563eb);background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-frv-comment .sv-frv-btn{justify-self:end}.sv-frv-send{display:flex;align-items:center;justify-content:flex-end;gap:12px;flex-wrap:wrap}.sv-frv-attach{display:inline-flex;align-items:center;gap:4px;margin-inline-end:auto}.sv-frv-internal{display:inline-flex;align-items:center;gap:4px;font-size:12px;color:var(--sg-muted, #64748b);cursor:pointer}.sv-frv-files{list-style:none;margin:6px 0 0;padding:0;display:flex;flex-direction:column;gap:3px}.sv-frv-replies-open{display:inline-flex;align-items:center;gap:4px}.sv-frv-replies{display:flex;flex-direction:column;gap:6px;padding:8px;border:1px solid var(--sg-border, #e2e8f0);border-radius:8px;background:var(--sg-bg, #fff)}.sv-frv-replies-search,.sv-frv-replies-save input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid var(--sg-border, #e2e8f0);border-radius:6px;background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a);min-width:0}.sv-frv-replies-list{list-style:none;margin:0;padding:0;max-height:220px;overflow:auto;display:flex;flex-direction:column;gap:2px}.sv-frv-reply{display:flex;flex-direction:column;gap:2px;width:100%;text-align:start;padding:6px 8px;border:0;border-radius:6px;background:none;font:inherit;font-size:13px;color:inherit;cursor:pointer}.sv-frv-reply:hover,.sv-frv-reply:focus-visible{background:var(--sg-hover, #f1f5f9)}.sv-frv-reply span{color:var(--sg-muted, #64748b);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-frv-replies-save{display:flex;gap:6px}.sv-frv-replies-save input{flex:1}.sv-frv-files li{display:flex;align-items:baseline;gap:6px;min-width:0;overflow-wrap:anywhere}.sv-frv-files a{color:var(--sg-accent, #2563eb)}.sv-frv-files.is-draft{margin:0;font-size:12px}.sv-frv-internal-tag{margin-inline-start:6px;padding:0 6px;border-radius:999px;font-size:11px;font-weight:600;color:#92400e;background:#fef3c7}.sv-frv-item.is-comment.is-internal .sv-frv-item-body{background:color-mix(in srgb,#f59e0b 12%,transparent)}.sv-frv-gone{color:var(--sg-muted, #64748b)}.sv-frv-footer{display:flex;align-items:center;gap:6px;width:100%}.sv-frv-pos{flex:1;font-size:13px;color:var(--sg-muted, #64748b)}.sv-frv-btn{display:inline-flex;align-items:center;justify-content:center;height:32px;min-width:32px;padding:0 12px;font:inherit;font-size:13px;cursor:pointer;border:1px solid var(--sg-border, #e2e8f0);border-radius:var(--sg-radius, 6px);background:var(--sg-bg, #fff);color:var(--sg-fg, #0f172a)}.sv-frv-btn:disabled{opacity:.4;cursor:default}.sv-frv-btn.is-primary{background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);border-color:var(--sg-fg, #0f172a)}.sv-frv-btn.is-danger{color:var(--sg-danger, #b91c1c)}@media(max-width:760px){.sv-frv-layout{grid-template-columns:minmax(0,1fr)}.sv-frv-activity{position:static;padding-inline-start:0;border-inline-start:0;border-top:1px solid var(--sg-border, #e2e8f0);padding-top:12px}}@media(max-width:600px){:global(.sv-modal:has(.sv-frv-layout)){width:100vw!important;max-width:100vw;height:100dvh;max-height:100dvh;border-radius:0}}.sv-frv-apps{display:flex;flex-wrap:wrap;gap:14px;justify-content:flex-end;margin:0 0 8px}.sv-frv-app{display:inline-flex;align-items:center;gap:5px}
|
|
275
293
|
</style>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{createDismissableLayer,portalToBody}from"@svgrid/grid";import{onMount}from"svelte";import{fieldPropsOf}from"./registry.svelte";import{addSelectOptions}from"./field-ops";import{OPTION_CYCLE,safeColor,textOn}from"./palette";import{getFieldUsers}from"./sources.svelte";import UserFace from"./UserFace.svelte";import{bm}from"./messages.svelte";import{phoneSheet}from"./phone-sheet";let{value,typed=false,row,columnDef,columnId,grid,onChange,onCommit,onCancel,onCommitAndMove,addOptions=true}=$props();const def=$derived(columnDef??{});const isUser=$derived(def.fieldType==="user");const multiple=$derived(isUser?!!fieldPropsOf(def).multiple:def.fieldType==="multiSelect");const declared=def.fieldType==="user"?getFieldUsers().map(u=>({value:u.id,label:u.name,user:u})):(fieldPropsOf(def).options??[]).map(o=>({value:String(o.value),...o.label?{label:o.label}:{},...o.color?{color:o.color}:{}}));let added=$state([]);const options=$derived([...declared,...added]);const start=typed?row?.[String(columnDef?.field??"")]:value;let picked=$state((Array.isArray(start)?start:start==null||start===""?[]:[start]).map(String));let search=$state(typed?String(value??""):"");let active=$state(0);let finished=false;const labelOf=o=>o.label??o.value;const byValue=$derived(new Map(options.map(o=>[o.value,o])));const shown=$derived.by(()=>{const q=search.trim().toLowerCase();return options.filter(o=>(!multiple||!picked.includes(o.value))&&(!q||labelOf(o).toLowerCase().includes(q)))});const newValue=$derived.by(()=>{const t=search.trim();return t&&addOptions&&!isUser&&!options.some(o=>labelOf(o).toLowerCase()===t.toLowerCase()||o.value.toLowerCase()===t.toLowerCase())?t:null});const count=$derived(shown.length+(newValue?1:0));$effect(()=>{if(active>=count)active=Math.max(0,count-1)});let anchor=$state(null);let input=$state(null);let list=$state(null);let panel=$state(null);let rect=$state(null);const sheet=phoneSheet();let backdrop=$state(null);const PANEL_HEIGHT=340;function place(){const cell=anchor?.closest("td")??anchor;if(!cell)return;const r=cell.getBoundingClientRect();const width=Math.min(Math.max(r.width+2,260),window.innerWidth-16);const left=Math.max(8,Math.min(r.left-1,window.innerWidth-width-8));const top=Math.max(8,Math.min(r.top-1,window.innerHeight-PANEL_HEIGHT-8));rect={top,left,width,maxHeight:window.innerHeight-top-8}}onMount(()=>{if(!multiple&&picked.length)active=Math.max(0,shown.findIndex(o=>o.value===picked[0]));place();const takeFocus=()=>{if(!input||document.activeElement===input||sheet&&!search)return;input.focus({preventScroll:true});input.setSelectionRange(search.length,search.length)};queueMicrotask(takeFocus);const frame=requestAnimationFrame(takeFocus);const onScroll=e=>{if(!panel?.contains(e.target))place()};const onDown=e=>{const t=e.target;if(panel?.contains(t)||anchor?.contains(t)||backdrop?.contains(t))return;keep()};window.addEventListener("resize",place);window.addEventListener("scroll",onScroll,true);document.addEventListener("pointerdown",onDown,true);const layer=createDismissableLayer({element:()=>[panel??null,anchor??null],onDismiss:()=>{},closeOnEscape:false,closeOnOutside:false});layer.activate();return()=>{layer.release();cancelAnimationFrame(frame);window.removeEventListener("resize",place);window.removeEventListener("scroll",onScroll,true);document.removeEventListener("pointerdown",onDown,true)}});const current=()=>multiple?[...picked]:picked[0]??null;function finish(how){if(finished)return;finished=true;if(how==="cancel")return onCancel();const v=current();const g=grid;const id=columnId;const used=added.filter(o=>picked.includes(o.value));if(how==="commit")onCommit(v);else if(onCommitAndMove)onCommitAndMove(v,how==="next"?1:-1);else onCommit(v);if(used.length&&g)addSelectOptions(g,id,used)}const keep=()=>finish("commit");function choose(i){let v;if(i<shown.length)v=shown[i].value;else if(newValue){v=newValue;added=[...added,{value:v,color:OPTION_CYCLE[options.length%OPTION_CYCLE.length]}]}else return;search="";if(!multiple){picked=[v];return keep()}picked=[...picked,v];onChange?.(current());active=0}function remove(v){picked=picked.filter(x=>x!==v);onChange?.(current());input?.focus()}function move(by){if(!count)return;active=(active+by+count)%count;queueMicrotask(()=>list?.querySelector(`[data-i="${active}"]`)?.scrollIntoView({block:"nearest"}))}function onKey(e){if(e.isComposing)return;if(e.key==="ArrowDown")move(1);else if(e.key==="ArrowUp")move(-1);else if(e.key==="Enter")count?choose(active):keep();else if(e.key==="Escape")multiple?keep():finish("cancel");else if(e.key==="Tab")finish(e.shiftKey?"prev":"next");else if(e.key==="Backspace"&&!search&&multiple&&picked.length)remove(picked[picked.length-1]);else if((e.key==="Backspace"||e.key==="Delete")&&!search&&!multiple){picked=[];keep()}else{e.stopPropagation();return}e.preventDefault();e.stopPropagation()}const inputValue=e=>e.currentTarget.value;const listId=`sv-fse-${Math.random().toString(36).slice(2,8)}`;
|
|
2
|
+
import{createDismissableLayer,portalToBody}from"@svgrid/grid";import{onMount}from"svelte";import{fieldPropsOf}from"./registry.svelte";import{canPickChoice}from"./field-access.svelte";import{recordOf}from"./people-rule";import{addSelectOptions}from"./field-ops";import{OPTION_CYCLE,safeColor,textOn}from"./palette";import{getFieldUsers}from"./sources.svelte";import UserFace from"./UserFace.svelte";import{bm}from"./messages.svelte";import{phoneSheet}from"./phone-sheet";let{value,typed=false,row,columnDef,columnId,grid,onChange,onCommit,onCancel,onCommitAndMove,addOptions=true}=$props();const def=$derived(columnDef??{});const isUser=$derived(def.fieldType==="user");const multiple=$derived(isUser?!!fieldPropsOf(def).multiple:def.fieldType==="multiSelect");const declared=def.fieldType==="user"?getFieldUsers().map(u=>({value:u.id,label:u.name,user:u})):(fieldPropsOf(def).options??[]).map(o=>({value:String(o.value),...o.label?{label:o.label}:{},...o.color?{color:o.color}:{}})).filter(o=>def.fieldType==="user"||canPickChoice(def,o.value,recordOf(row)));let added=$state([]);const options=$derived([...declared,...added]);const start=typed?row?.[String(columnDef?.field??"")]:value;let picked=$state((Array.isArray(start)?start:start==null||start===""?[]:[start]).map(String));let search=$state(typed?String(value??""):"");let active=$state(0);let finished=false;const labelOf=o=>o.label??o.value;const byValue=$derived(new Map(options.map(o=>[o.value,o])));const shown=$derived.by(()=>{const q=search.trim().toLowerCase();return options.filter(o=>(!multiple||!picked.includes(o.value))&&(!q||labelOf(o).toLowerCase().includes(q)))});const newValue=$derived.by(()=>{const t=search.trim();return t&&addOptions&&!isUser&&!options.some(o=>labelOf(o).toLowerCase()===t.toLowerCase()||o.value.toLowerCase()===t.toLowerCase())?t:null});const count=$derived(shown.length+(newValue?1:0));$effect(()=>{if(active>=count)active=Math.max(0,count-1)});let anchor=$state(null);let input=$state(null);let list=$state(null);let panel=$state(null);let rect=$state(null);const sheet=phoneSheet();let backdrop=$state(null);const PANEL_HEIGHT=340;function place(){const cell=anchor?.closest("td")??anchor;if(!cell)return;const r=cell.getBoundingClientRect();const width=Math.min(Math.max(r.width+2,260),window.innerWidth-16);const left=Math.max(8,Math.min(r.left-1,window.innerWidth-width-8));const top=Math.max(8,Math.min(r.top-1,window.innerHeight-PANEL_HEIGHT-8));rect={top,left,width,maxHeight:window.innerHeight-top-8}}onMount(()=>{if(!multiple&&picked.length)active=Math.max(0,shown.findIndex(o=>o.value===picked[0]));place();const takeFocus=()=>{if(!input||document.activeElement===input||sheet&&!search)return;input.focus({preventScroll:true});input.setSelectionRange(search.length,search.length)};queueMicrotask(takeFocus);const frame=requestAnimationFrame(takeFocus);const onScroll=e=>{if(!panel?.contains(e.target))place()};const onDown=e=>{const t=e.target;if(panel?.contains(t)||anchor?.contains(t)||backdrop?.contains(t))return;keep()};window.addEventListener("resize",place);window.addEventListener("scroll",onScroll,true);document.addEventListener("pointerdown",onDown,true);const layer=createDismissableLayer({element:()=>[panel??null,anchor??null],onDismiss:()=>{},closeOnEscape:false,closeOnOutside:false});layer.activate();return()=>{layer.release();cancelAnimationFrame(frame);window.removeEventListener("resize",place);window.removeEventListener("scroll",onScroll,true);document.removeEventListener("pointerdown",onDown,true)}});const current=()=>multiple?[...picked]:picked[0]??null;function finish(how){if(finished)return;finished=true;if(how==="cancel")return onCancel();const v=current();const g=grid;const id=columnId;const used=added.filter(o=>picked.includes(o.value));if(how==="commit")onCommit(v);else if(onCommitAndMove)onCommitAndMove(v,how==="next"?1:-1);else onCommit(v);if(used.length&&g)addSelectOptions(g,id,used)}const keep=()=>finish("commit");function choose(i){let v;if(i<shown.length)v=shown[i].value;else if(newValue){v=newValue;added=[...added,{value:v,color:OPTION_CYCLE[options.length%OPTION_CYCLE.length]}]}else return;search="";if(!multiple){picked=[v];return keep()}picked=[...picked,v];onChange?.(current());active=0}function remove(v){picked=picked.filter(x=>x!==v);onChange?.(current());input?.focus()}function move(by){if(!count)return;active=(active+by+count)%count;queueMicrotask(()=>list?.querySelector(`[data-i="${active}"]`)?.scrollIntoView({block:"nearest"}))}function onKey(e){if(e.isComposing)return;if(e.key==="ArrowDown")move(1);else if(e.key==="ArrowUp")move(-1);else if(e.key==="Enter")count?choose(active):keep();else if(e.key==="Escape")multiple?keep():finish("cancel");else if(e.key==="Tab")finish(e.shiftKey?"prev":"next");else if(e.key==="Backspace"&&!search&&multiple&&picked.length)remove(picked[picked.length-1]);else if((e.key==="Backspace"||e.key==="Delete")&&!search&&!multiple){picked=[];keep()}else{e.stopPropagation();return}e.preventDefault();e.stopPropagation()}const inputValue=e=>e.currentTarget.value;const listId=`sv-fse-${Math.random().toString(36).slice(2,8)}`;
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
|
|
@@ -24,7 +24,19 @@ export type RecordComment = {
|
|
|
24
24
|
* it, and the store keeps it from people outside the team (a client portal).
|
|
25
25
|
*/
|
|
26
26
|
internal?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Who voted it up and who down, by user id (a store with `vote`, or no
|
|
29
|
+
* store). A person has one vote on a comment, and none on their own.
|
|
30
|
+
*/
|
|
31
|
+
votes?: CommentVotes;
|
|
27
32
|
};
|
|
33
|
+
/** A comment's votes: the ids of the people who voted it up, and down. */
|
|
34
|
+
export type CommentVotes = {
|
|
35
|
+
up?: string[];
|
|
36
|
+
down?: string[];
|
|
37
|
+
};
|
|
38
|
+
/** A person's vote on a comment; null takes it back. */
|
|
39
|
+
export type CommentVote = 'up' | 'down' | null;
|
|
28
40
|
/** Which record a comment store is asked about, beyond its row id. */
|
|
29
41
|
export type RecordCommentContext = {
|
|
30
42
|
/** The table of `<SvBase tables>` the record is in; undefined for a single table or a plain grid. */
|
|
@@ -60,6 +72,12 @@ export type RecordCommentStore = {
|
|
|
60
72
|
files?: boolean;
|
|
61
73
|
/** It keeps internal notes: the comment box offers to mark one for the team only. */
|
|
62
74
|
internal?: boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Someone voted a comment up or down, or took their vote back (null). With
|
|
77
|
+
* it the record view shows Up and Down under each comment; without it a
|
|
78
|
+
* store's comments take no votes. `comment` is the comment with the vote.
|
|
79
|
+
*/
|
|
80
|
+
vote?: (rowId: string, comment: RecordComment, vote: CommentVote, api: unknown, context: RecordCommentContext) => void;
|
|
63
81
|
};
|
|
64
82
|
export type RecordChange = {
|
|
65
83
|
at: number;
|
|
@@ -223,6 +241,22 @@ export declare function addComment(ctrl: any, rowId: string, text: string, extra
|
|
|
223
241
|
export declare function ownsComment(comment: RecordComment, what: 'update' | 'remove'): boolean;
|
|
224
242
|
/** Change a comment's text. Only its author can; someone newly named in it hears of it. */
|
|
225
243
|
export declare function editComment(ctrl: any, rowId: string, id: string, text: string): void;
|
|
244
|
+
/** Whether comments take votes here: no store (they are kept in the page), or a store with `vote`. */
|
|
245
|
+
export declare const commentsTakeVotes: () => boolean;
|
|
246
|
+
/** The people who voted a comment up and down, each list without repeats. */
|
|
247
|
+
export declare function commentVotes(comment: RecordComment): {
|
|
248
|
+
up: string[];
|
|
249
|
+
down: string[];
|
|
250
|
+
};
|
|
251
|
+
/** The signed-in person's vote on a comment, or null. */
|
|
252
|
+
export declare function myCommentVote(comment: RecordComment): CommentVote;
|
|
253
|
+
/** Whether the signed-in person may vote a comment: someone signed in, not its author, where votes are kept. */
|
|
254
|
+
export declare function mayVoteComment(comment: RecordComment): boolean;
|
|
255
|
+
/**
|
|
256
|
+
* Vote a comment up or down. Pressing the vote a person already gave takes
|
|
257
|
+
* it back; the other vote replaces it. Nobody votes their own comment.
|
|
258
|
+
*/
|
|
259
|
+
export declare function voteComment(ctrl: any, rowId: string, id: string, vote: 'up' | 'down'): void;
|
|
226
260
|
/** Delete a comment. Only its author can. */
|
|
227
261
|
export declare function deleteComment(ctrl: any, rowId: string, id: string): void;
|
|
228
262
|
/** "just now", "5 minutes ago", "3 hours ago", else the date. */
|