@svgrid/enterprise 3.1.43 → 3.1.45

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.
Files changed (56) hide show
  1. package/dist/cdn/svgrid-enterprise.svelte-external.js +1 -1
  2. package/dist/designer/assets/{index-BWz7zwBp.js → index-BQO-FqUG.js} +214 -214
  3. package/dist/designer/index.html +1 -1
  4. package/dist/fields/BaseTableView.svelte +3 -2
  5. package/dist/fields/FieldEditor.svelte +1 -1
  6. package/dist/fields/FieldEditor.svelte.d.ts +3 -0
  7. package/dist/fields/FieldsHeaderEnd.svelte +1 -1
  8. package/dist/fields/FormulaInput.svelte +122 -0
  9. package/dist/fields/FormulaInput.svelte.d.ts +10 -0
  10. package/dist/fields/FormulaInputHarness.svelte +5 -0
  11. package/dist/fields/FormulaInputHarness.svelte.d.ts +11 -0
  12. package/dist/fields/NumberEditor.svelte +1 -1
  13. package/dist/fields/PasteFields.svelte +33 -0
  14. package/dist/fields/PasteFields.svelte.d.ts +6 -0
  15. package/dist/fields/PropertyInput.svelte +4 -8
  16. package/dist/fields/RecordView.svelte +38 -2
  17. package/dist/fields/SvBase.svelte +1 -1
  18. package/dist/fields/SvBase.svelte.d.ts +7 -0
  19. package/dist/fields/SvBaseForm.svelte +26 -2
  20. package/dist/fields/SvBaseForm.svelte.d.ts +4 -0
  21. package/dist/fields/SvBaseViewBar.svelte +2 -2
  22. package/dist/fields/base-import.js +2 -2
  23. package/dist/fields/celebrate.d.ts +29 -0
  24. package/dist/fields/celebrate.js +1 -0
  25. package/dist/fields/cell-colors.svelte.d.ts +17 -0
  26. package/dist/fields/cell-colors.svelte.js +1 -0
  27. package/dist/fields/comment-snippets.svelte.d.ts +35 -0
  28. package/dist/fields/comment-snippets.svelte.js +1 -0
  29. package/dist/fields/editor-request.svelte.d.ts +7 -0
  30. package/dist/fields/excel-habits.svelte.d.ts +98 -0
  31. package/dist/fields/excel-habits.svelte.js +1 -0
  32. package/dist/fields/form-suggestions.svelte.d.ts +29 -0
  33. package/dist/fields/form-suggestions.svelte.js +1 -0
  34. package/dist/fields/formula-docs.d.ts +24 -0
  35. package/dist/fields/formula-docs.js +1 -0
  36. package/dist/fields/index.d.ts +3 -0
  37. package/dist/fields/index.js +1 -1
  38. package/dist/fields/messages/fields.d.ts +28 -0
  39. package/dist/fields/messages/fields.js +1 -1
  40. package/dist/fields/messages/record.d.ts +16 -0
  41. package/dist/fields/messages/record.js +1 -1
  42. package/dist/fields/messages/shell.d.ts +22 -0
  43. package/dist/fields/messages/shell.js +1 -1
  44. package/dist/fields/messages/viewbar.d.ts +9 -0
  45. package/dist/fields/messages/viewbar.js +1 -1
  46. package/dist/fields/messages.svelte.d.ts +75 -0
  47. package/dist/fields/view-model.d.ts +3 -0
  48. package/dist/fields/view-model.js +1 -1
  49. package/dist/fields/viewbar/ColorPanel.svelte +54 -2
  50. package/dist/fields/viewbar/ColorPanel.svelte.d.ts +3 -0
  51. package/dist/node/studio.js +1 -1
  52. package/dist/version.d.ts +2 -2
  53. package/dist/version.js +1 -1
  54. package/dist/wc/sv-base-element.js +101 -95
  55. package/dist/wc/sv-sheet-element.js +43 -43
  56. package/package.json +3 -3
@@ -170,6 +170,13 @@ type $$ComponentProps = {
170
170
  readOnly?: boolean | BaseShare;
171
171
  /** The search box in the tab bar, over every table's records (default true; Ctrl+K focuses it). */
172
172
  search?: boolean;
173
+ /**
174
+ * Fireworks for a moment where someone finishes a record: a single select set
175
+ * to Done, Completed, Shipped, Paid or Won, or a Done checkbox ticked (see
176
+ * celebrate.ts). Default false; never for an undo, a block of cells, or
177
+ * someone whose system asks for less motion.
178
+ */
179
+ celebrate?: boolean;
173
180
  /**
174
181
  * What the signed-in person may do: `{ canCreate, canDelete, canEditSchema,
175
182
  * canEditViews, canComment, fields, viewsOnly }`. A table's own
@@ -1,7 +1,24 @@
1
1
  <script lang="ts">
2
- import{tick,untrack}from"svelte";import{cubicOut}from"svelte/easing";import{announce,getCellEditor}from"@svgrid/grid";import{fieldColumns,gridOf,primaryIdOf}from"./grid-access";import{newRowValues}from"./field-ops";import{linkHref}from"./links";import{compileFormConditions,formColumns,formControlOf,formPrefillKey,formValue,prefillValue,readFormPrefill,settleFormAnswers}from"./form-logic";import FieldInput from"./FieldInput.svelte";import FieldIcon from"./viewbar/FieldIcon.svelte";import{bm,bmCount}from"./messages.svelte";import{errorWords}from"./base-failure";let{api,fields,required=[],title,description="",submitLabel,defaults,conditions,prefill,prefillFields,footerText,footer,labels,help,layout="list",transition="slide",onSubmit}=$props();const ctrl=$derived(api?gridOf(api):void 0);const labelOf=c=>(labels?.[c.id]??"").trim()||c.header;const helpOf=c=>help&&Object.prototype.hasOwnProperty.call(help,c.id)?String(help[c.id]??""):c.def.description?String(c.def.description):"";const columns=$derived.by(()=>{if(!ctrl)return[];const all=formColumns(ctrl);if(!fields){const p=primaryIdOf(ctrl);return[...all.filter(c=>c.id===p),...all.filter(c=>c.id!==p)]}return fields.map(id=>all.find(c=>c.id===id)).filter(c=>!!c)});function placeholderFor(c){const t=c.fieldType??"";if(t==="singleSelect"||t==="multiSelect"||t==="user")return bm("record.formChoose");if(t==="date")return bm("record.formPickDate");if(t==="attachment")return bm("record.formAddFiles");if(t==="link")return bm("record.formLinkRecords");return bm("record.formTypeHere")}let formBox=$state(null);const uid=`sv-fform-${Math.random().toString(36).slice(2,8)}`;const controlIds=c=>({control:`${uid}-${c.id}`,error:`${uid}-${c.id}-error`,hint:`${uid}-${c.id}-hint`});const hasInput=c=>c.def.editorType==="checkbox"||!!formControlOf(c.def,!!getCellEditor(String(c.def.editorType??"text")));let draft=$state({});let editing=$state(null);let errors=$state({});let sent=$state(false);let titleBox=$state(null);let busy=$state(false);let failure=$state("");let seed=null;let prefilled={};function linkable(cols){if(!prefillFields)return[...cols];const allowed=new Set(prefillFields.map(n=>n.trim().toLowerCase()));return cols.filter(c=>allowed.has(c.id.toLowerCase())||allowed.has(c.header.trim().toLowerCase()))}let context={};let hidden=$state.raw(new Set);let linkHidden=$state.raw(new Set);const isBlank=v=>v==null||v===""||Array.isArray(v)&&v.length===0;const tests=$derived(ctrl?compileFormConditions(conditions,fieldColumns(ctrl)):new Map);const shown=$derived(columns.filter(c=>!hidden.has(c.id)&&!linkHidden.has(c.id)));function settle(next2){const out=settleFormAnswers(next2,columns,tests,{initial:prefilled,context,was:hidden});hidden=out.hidden;draft=out.draft}function startRecord(){if(!ctrl)return;const cfg=ctrl.props.rowAdder;const fromAdder=cfg&&typeof cfg==="object"&&typeof cfg.defaults==="function"?cfg.defaults():{};const base={...defaults?.()??{},...fromAdder};seed=base;const start=newRowValues(ctrl,base);const next2={};for(const c of columns){const v=start[c.field];if(v!==void 0&&!isBlank(v))next2[c.field]=Array.isArray(v)?v.slice():v}const fromLink=readFormPrefill(prefill,linkable(columns));for(const c of columns){if(!(c.id in fromLink.values))continue;const v=prefillValue(c,fromLink.values[c.id],next2);if(v!==void 0)next2[c.field]=v}linkHidden=new Set(columns.filter(c=>fromLink.hide.has(c.id)&&!isBlank(next2[c.field])).map(c=>c.id));const asked=new Set(columns.map(c=>c.field));context=Object.fromEntries(Object.entries(start).filter(([k])=>!asked.has(k)));prefilled={...next2};hidden=new Set;settle(next2)}const prefillKey=$derived(formPrefillKey(prefill));let appliedKey=null;$effect.pre(()=>{const key=prefillKey;if(!ctrl||seed&&key===appliedKey)return;untrack(()=>{const fresh=!seed;appliedKey=key;if(fresh)startRecord();else again()})});const parsed=(c,raw)=>formValue(c,raw,draft);function set(c,v){settle({...draft,[c.field]:parsed(c,v)});const stale=Object.keys(errors).filter(id=>id===c.id||hidden.has(id));if(stale.length){const rest={...errors};for(const id of stale)delete rest[id];errors=rest}}const FORMATS={email:{kind:"email",message:()=>bm("record.formInvalidEmail")},url:{kind:"url",message:()=>bm("record.formInvalidUrl")},phone:{kind:"phone",message:()=>bm("record.formInvalidPhone")}};function problem(c,v){const blank=isBlank(v);if(blank&&required.includes(c.id))return bm("record.formFieldRequired",{field:labelOf(c)});const format=FORMATS[c.fieldType??""];if(!blank&&format&&!linkHref(format.kind,v))return format.message();const validate=c.def.validate;if(typeof validate==="function"){const verdict=validate({value:v,row:draft,rowIndex:-1,column:{id:c.id,columnDef:c.def}});if(verdict===false)return bm("record.formFieldInvalid",{field:labelOf(c)});if(typeof verdict==="string"&&verdict)return verdict}return""}function stopEditing(c){editing=null;setTimeout(()=>{const now=document.activeElement;if(editing!=null||now&&now!==document.body)return;const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===c.id);box?.querySelector(".sv-frv-open")?.focus()},0)}function editBeside(c,dir2){if(layout==="steps"){editing=null;return}const at2=shown.findIndex(x=>x.id===c.id);const next2=shown[at2+dir2];editing=next2&&next2.def.editorType!=="checkbox"?next2.id:null}function given(){const out={};for(const[field,v]of Object.entries(draft)){if(!isBlank(v)||field in prefilled)out[field]=v}return out}const steps=$derived(layout==="steps");let step=$state(0);let dir=$state(1);const at=$derived(Math.max(0,Math.min(step,shown.length-1)));const current=$derived(shown[at]);const lastStep=$derived(at>=shown.length-1);const lessMotion=typeof window!=="undefined"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function enter(_node){if(transition==="none"||lessMotion)return{duration:0};if(transition==="fade")return{duration:240,css:t=>`opacity: ${t}`};const from=44*dir;return{duration:320,easing:cubicOut,css:(t,u)=>`opacity: ${t}; transform: translateX(${u*from}px)`}}function focusField(c){if(!c)return;const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===c.id);box?.querySelector("input, textarea, select, button")?.focus()}async function moved(){await tick();announce(bm("record.formStepOf",{n:at+1,count:shown.length}));focusField(current)}async function next(){const c=current;if(!c||busy)return;editing=null;failure="";const why=problem(c,draft[c.field]);if(why){errors={...errors,[c.id]:why};announce(why,{assertive:true});await tick();focusField(c);return}if(lastStep)return;dir=1;step=at+1;await moved()}function back(){if(at===0)return;editing=null;dir=-1;step=at-1;void moved()}function stepKey(e){if(!steps||e.key!=="Enter"||e.shiftKey||e.isComposing||editing!=null)return;const target=e.target;if(target.tagName==="TEXTAREA"||target.tagName==="BUTTON"||target.isContentEditable)return;e.preventDefault();if(lastStep)formBox?.requestSubmit();else void next()}async function submit(e){e.preventDefault();if(!ctrl||busy)return;if(steps&&!lastStep){void next();return}editing=null;failure="";const found={};for(const c of columns){if(hidden.has(c.id))continue;const why=problem(c,draft[c.field]);if(why)found[c.id]=why}errors=found;if(Object.keys(found).length){if([...linkHidden].some(id=>found[id]))linkHidden=new Set([...linkHidden].filter(id=>!found[id]));if(steps){await tick();const first2=shown.findIndex(c=>found[c.id]);if(first2>=0&&first2!==at){dir=-1;step=first2}}announce(bmCount("record.formProblems",Object.keys(found).length),{assertive:true});await tick();const first=shown.find(c=>found[c.id]);const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===first?.id);box?.querySelector("input, textarea, select, button")?.focus();return}if(shown.length&&shown.every(c=>isBlank(draft[c.field]))){failure=bm("record.formEmpty");return}if(!seed)startRecord();const row=newRowValues(ctrl,{...seed,...given()});for(const c of columns)if(hidden.has(c.id))delete row[c.field];api.addRow(row,"bottom");ctrl.props.onRowAdd?.({row});let result;try{result=onSubmit?.(row)}catch(err){return fail(row,err)}if(result&&typeof result.then==="function"){busy=true;try{await result}catch(err){return fail(row,err)}finally{busy=false}}sent=true;announce(bm("record.formAdded"));await tick();titleBox?.focus()}function fail(row,err){const at2=ctrl?ctrl.internalData.indexOf(row):-1;if(at2>=0)api.removeRows([at2]);failure=err instanceof Error&&err.message?errorWords(err):bm("record.formSendFailed");void tick().then(()=>{if(document.activeElement===document.body)formBox?.querySelector(".sv-fform-submit")?.focus()})}async function again(){seed=null;errors={};failure="";step=0;dir=1;startRecord();sent=false;await tick();titleBox?.focus()}
2
+ import{tick,untrack}from"svelte";import{cubicOut}from"svelte/easing";import{announce,getCellEditor}from"@svgrid/grid";import{fieldColumns,gridOf,primaryIdOf}from"./grid-access";import{newRowValues}from"./field-ops";import{linkHref}from"./links";import{compileFormConditions,formColumns,formControlOf,formPrefillKey,formValue,prefillValue,readFormPrefill,settleFormAnswers}from"./form-logic";import FieldInput from"./FieldInput.svelte";import FieldIcon from"./viewbar/FieldIcon.svelte";import{bm,bmCount}from"./messages.svelte";import{errorWords}from"./base-failure";import{formSuggestions}from"./form-suggestions.svelte";let{api,fields,required=[],title,description="",submitLabel,defaults,conditions,prefill,prefillFields,footerText,footer,labels,help,layout="list",transition="slide",onSubmit}=$props();const ctrl=$derived(api?gridOf(api):void 0);const labelOf=c=>(labels?.[c.id]??"").trim()||c.header;const helpOf=c=>help&&Object.prototype.hasOwnProperty.call(help,c.id)?String(help[c.id]??""):c.def.description?String(c.def.description):"";const columns=$derived.by(()=>{if(!ctrl)return[];const all=formColumns(ctrl);if(!fields){const p=primaryIdOf(ctrl);return[...all.filter(c=>c.id===p),...all.filter(c=>c.id!==p)]}return fields.map(id=>all.find(c=>c.id===id)).filter(c=>!!c)});function placeholderFor(c){const t=c.fieldType??"";if(t==="singleSelect"||t==="multiSelect"||t==="user")return bm("record.formChoose");if(t==="date")return bm("record.formPickDate");if(t==="attachment")return bm("record.formAddFiles");if(t==="link")return bm("record.formLinkRecords");return bm("record.formTypeHere")}let formBox=$state(null);const uid=`sv-fform-${Math.random().toString(36).slice(2,8)}`;const controlIds=c=>({control:`${uid}-${c.id}`,error:`${uid}-${c.id}-error`,hint:`${uid}-${c.id}-hint`});const hasInput=c=>c.def.editorType==="checkbox"||!!formControlOf(c.def,!!getCellEditor(String(c.def.editorType??"text")));let draft=$state({});let editing=$state(null);let errors=$state({});let sent=$state(false);let titleBox=$state(null);let busy=$state(false);let failure=$state("");let seed=null;let prefilled={};function linkable(cols){if(!prefillFields)return[...cols];const allowed=new Set(prefillFields.map(n=>n.trim().toLowerCase()));return cols.filter(c=>allowed.has(c.id.toLowerCase())||allowed.has(c.header.trim().toLowerCase()))}let context={};let hidden=$state.raw(new Set);let linkHidden=$state.raw(new Set);const isBlank=v=>v==null||v===""||Array.isArray(v)&&v.length===0;const tests=$derived(ctrl?compileFormConditions(conditions,fieldColumns(ctrl)):new Map);const shown=$derived(columns.filter(c=>!hidden.has(c.id)&&!linkHidden.has(c.id)));function settle(next2){const out=settleFormAnswers(next2,columns,tests,{initial:prefilled,context,was:hidden});hidden=out.hidden;draft=out.draft}function startRecord(){if(!ctrl)return;const cfg=ctrl.props.rowAdder;const fromAdder=cfg&&typeof cfg==="object"&&typeof cfg.defaults==="function"?cfg.defaults():{};const base={...defaults?.()??{},...fromAdder};seed=base;const start=newRowValues(ctrl,base);const next2={};for(const c of columns){const v=start[c.field];if(v!==void 0&&!isBlank(v))next2[c.field]=Array.isArray(v)?v.slice():v}const fromLink=readFormPrefill(prefill,linkable(columns));for(const c of columns){if(!(c.id in fromLink.values))continue;const v=prefillValue(c,fromLink.values[c.id],next2);if(v!==void 0)next2[c.field]=v}linkHidden=new Set(columns.filter(c=>fromLink.hide.has(c.id)&&!isBlank(next2[c.field])).map(c=>c.id));const asked=new Set(columns.map(c=>c.field));context=Object.fromEntries(Object.entries(start).filter(([k])=>!asked.has(k)));prefilled={...next2};hidden=new Set;settle(next2)}const prefillKey=$derived(formPrefillKey(prefill));let appliedKey=null;$effect.pre(()=>{const key=prefillKey;if(!ctrl||seed&&key===appliedKey)return;untrack(()=>{const fresh=!seed;appliedKey=key;if(fresh)startRecord();else again()})});const parsed=(c,raw)=>formValue(c,raw,draft);function set(c,v){settle({...draft,[c.field]:parsed(c,v)});const stale=Object.keys(errors).filter(id=>id===c.id||hidden.has(id));if(stale.length){const rest={...errors};for(const id of stale)delete rest[id];errors=rest}}const FORMATS={email:{kind:"email",message:()=>bm("record.formInvalidEmail")},url:{kind:"url",message:()=>bm("record.formInvalidUrl")},phone:{kind:"phone",message:()=>bm("record.formInvalidPhone")}};function problem(c,v){const blank=isBlank(v);if(blank&&required.includes(c.id))return bm("record.formFieldRequired",{field:labelOf(c)});const format=FORMATS[c.fieldType??""];if(!blank&&format&&!linkHref(format.kind,v))return format.message();const validate=c.def.validate;if(typeof validate==="function"){const verdict=validate({value:v,row:draft,rowIndex:-1,column:{id:c.id,columnDef:c.def}});if(verdict===false)return bm("record.formFieldInvalid",{field:labelOf(c)});if(typeof verdict==="string"&&verdict)return verdict}return""}function stopEditing(c){editing=null;setTimeout(()=>{const now=document.activeElement;if(editing!=null||now&&now!==document.body)return;const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===c.id);box?.querySelector(".sv-frv-open")?.focus()},0)}function editBeside(c,dir2){if(layout==="steps"){editing=null;return}const at2=shown.findIndex(x=>x.id===c.id);const next2=shown[at2+dir2];editing=next2&&next2.def.editorType!=="checkbox"?next2.id:null}function given(){const out={};for(const[field,v]of Object.entries(draft)){if(!isBlank(v)||field in prefilled)out[field]=v}return out}const steps=$derived(layout==="steps");let step=$state(0);let dir=$state(1);const at=$derived(Math.max(0,Math.min(step,shown.length-1)));const current=$derived(shown[at]);const lastStep=$derived(at>=shown.length-1);const lessMotion=typeof window!=="undefined"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function enter(_node){if(transition==="none"||lessMotion)return{duration:0};if(transition==="fade")return{duration:240,css:t=>`opacity: ${t}`};const from=44*dir;return{duration:320,easing:cubicOut,css:(t,u)=>`opacity: ${t}; transform: translateX(${u*from}px)`}}function focusField(c){if(!c)return;const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===c.id);box?.querySelector("input, textarea, select, button")?.focus()}async function moved(){await tick();announce(bm("record.formStepOf",{n:at+1,count:shown.length}));focusField(current)}async function next(){const c=current;if(!c||busy)return;editing=null;failure="";const why=problem(c,draft[c.field]);if(why){errors={...errors,[c.id]:why};announce(why,{assertive:true});await tick();focusField(c);return}if(lastStep)return;dir=1;step=at+1;await moved()}function back(){if(at===0)return;editing=null;dir=-1;step=at-1;void moved()}function stepKey(e){if(!steps||e.key!=="Enter"||e.shiftKey||e.isComposing||editing!=null)return;const target=e.target;if(target.tagName==="TEXTAREA"||target.tagName==="BUTTON"||target.isContentEditable)return;e.preventDefault();if(lastStep)formBox?.requestSubmit();else void next()}async function submit(e){e.preventDefault();if(!ctrl||busy)return;if(steps&&!lastStep){void next();return}editing=null;failure="";const found={};for(const c of columns){if(hidden.has(c.id))continue;const why=problem(c,draft[c.field]);if(why)found[c.id]=why}errors=found;if(Object.keys(found).length){if([...linkHidden].some(id=>found[id]))linkHidden=new Set([...linkHidden].filter(id=>!found[id]));if(steps){await tick();const first2=shown.findIndex(c=>found[c.id]);if(first2>=0&&first2!==at){dir=-1;step=first2}}announce(bmCount("record.formProblems",Object.keys(found).length),{assertive:true});await tick();const first=shown.find(c=>found[c.id]);const box=[...formBox?.querySelectorAll("[data-form-field]")??[]].find(el=>el.dataset.formField===first?.id);box?.querySelector("input, textarea, select, button")?.focus();return}if(shown.length&&shown.every(c=>isBlank(draft[c.field]))){failure=bm("record.formEmpty");return}if(!seed)startRecord();const row=newRowValues(ctrl,{...seed,...given()});for(const c of columns)if(hidden.has(c.id))delete row[c.field];api.addRow(row,"bottom");ctrl.props.onRowAdd?.({row});let result;try{result=onSubmit?.(row)}catch(err){return fail(row,err)}if(result&&typeof result.then==="function"){busy=true;try{await result}catch(err){return fail(row,err)}finally{busy=false}}sent=true;announce(bm("record.formAdded"));await tick();titleBox?.focus()}function fail(row,err){const at2=ctrl?ctrl.internalData.indexOf(row):-1;if(at2>=0)api.removeRows([at2]);failure=err instanceof Error&&err.message?errorWords(err):bm("record.formSendFailed");void tick().then(()=>{if(document.activeElement===document.body)formBox?.querySelector(".sv-fform-submit")?.focus()})}const suggester=$derived(formSuggestions());const subject=$derived(suggester?shown.find(c=>!c.fieldType||c.fieldType==="text"||c.fieldType==="longText"):void 0);let suggestions=$state([]);let openSuggestion=$state(null);let solvedDone=$state(false);let askedFor="";let suggestTimer;$effect(()=>{const s=suggester;const c=subject;const text=c?String(draft[c.field]??"").trim():"";untrack(()=>{if(!s||text.length<3){suggestions=[];askedFor="";return}if(text===askedFor)return;clearTimeout(suggestTimer);suggestTimer=setTimeout(async()=>{askedFor=text;try{const got=await s.list(ctrl?.props?.baseTableId,text,{...draft});if(askedFor===text)suggestions=(Array.isArray(got)?got:[]).slice(0,5)}catch{suggestions=[]}},250)})});async function solvedBy(item){try{await suggester?.solved?.(ctrl?.props?.baseTableId,item.id)}catch{}solvedDone=true;announce(bm("record.formSolvedNote"));await tick();titleBox?.focus()}async function again(){solvedDone=false;suggestions=[];openSuggestion=null;askedFor="";seed=null;errors={};failure="";step=0;dir=1;startRecord();sent=false;await tick();titleBox?.focus()}
3
3
  </script>
4
4
 
5
+ {#snippet suggestBlock()}
6
+ <div class="sv-fform-suggest" role="region" aria-label={bm('record.formSuggestTitle')} aria-live="polite">
7
+ <p class="sv-fform-suggest-title">{bm('record.formSuggestTitle')}</p>
8
+ <ul>
9
+ {#each suggestions as item (item.id)}
10
+ <li>
11
+ <button type="button" class="sv-fform-suggest-item" aria-expanded={openSuggestion === item.id} onclick={() => (openSuggestion = openSuggestion === item.id ? null : item.id)}>{item.title}</button>
12
+ {#if openSuggestion === item.id}
13
+ <div class="sv-fform-suggest-text">{item.text}</div>
14
+ <button type="button" class="sv-fform-solved" onclick={() => void solvedBy(item)}>{bm('record.formSolved')}</button>
15
+ {/if}
16
+ </li>
17
+ {/each}
18
+ </ul>
19
+ </div>
20
+ {/snippet}
21
+
5
22
  {#snippet fieldBlock(c: FieldColumn)}
6
23
  {@const v = draft[c.field]}
7
24
  {@const ids = controlIds(c)}
@@ -35,6 +52,7 @@ import{tick,untrack}from"svelte";import{cubicOut}from"svelte/easing";import{anno
35
52
  {#if errors[c.id]}<p class="sv-fform-error" id={ids.error}>{errors[c.id]}</p>{/if}
36
53
  {#if helpOf(c)}<p class="sv-fform-hint" id={ids.hint}>{helpOf(c)}</p>{/if}
37
54
  </div>
55
+ {#if subject && c.id === subject.id && suggestions.length}{@render suggestBlock()}{/if}
38
56
  {/snippet}
39
57
 
40
58
  {#if ctrl}
@@ -45,6 +63,12 @@ import{tick,untrack}from"svelte";import{cubicOut}from"svelte/easing";import{anno
45
63
  <p class="sv-fform-desc">{bm('record.formAdded')}</p>
46
64
  <button type="button" class="sv-fform-submit" onclick={again}>{bm('record.formSubmitAnother')}</button>
47
65
  </div>
66
+ {:else if solvedDone}
67
+ <div class="sv-fform sv-fform-done">
68
+ <h2 class="sv-fform-title" tabindex="-1" bind:this={titleBox}>{bm('record.formSolvedTitle')}</h2>
69
+ <p class="sv-fform-desc">{bm('record.formSolvedNote')}</p>
70
+ <button type="button" class="sv-fform-submit" onclick={again}>{bm('record.formAskAnother')}</button>
71
+ </div>
48
72
  {:else if steps}
49
73
  <form class="sv-fform is-steps" bind:this={formBox} onsubmit={submit} onkeydown={stepKey} novalidate>
50
74
  <div class="sv-fform-progress" role="progressbar" aria-valuemin={1} aria-valuemax={Math.max(1, shown.length)} aria-valuenow={at + 1} aria-label={bm('record.formStepOf', { n: at + 1, count: shown.length })}>
@@ -97,5 +121,5 @@ import{tick,untrack}from"svelte";import{cubicOut}from"svelte/easing";import{anno
97
121
  {/if}
98
122
 
99
123
  <style>
100
- .sv-fform-footer{margin-top:16px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fform-footer p{margin:0 0 6px}.sv-fform-wrap{height:100%;overflow:auto;box-sizing:border-box;padding:24px 16px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 4%,var(--sg-bg, #fff));font-family:var(--sg-font, inherit);color:var(--sg-fg, #0f172a)}.sv-fform{max-width:640px;margin:0 auto;padding:24px 28px;display:flex;flex-direction:column;gap:18px;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #e2e8f0);border-radius:12px}.sv-fform-title{margin:0;font-size:22px}.sv-fform-title:focus-visible{outline:2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb));outline-offset:2px}.sv-fform-desc{margin:-10px 0 0;color:var(--sg-muted, #64748b)}.sv-fform-field{display:flex;flex-direction:column;gap:6px}.sv-fform-label{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600}.sv-fform-req{color:var(--sg-danger, #dc2626)}.sv-fform-field.is-missing :global(.sv-frv-box){border-color:var(--sg-danger, #dc2626)}.sv-fform-error{margin:0;font-size:12px;color:var(--sg-danger, #dc2626)}.sv-fform-hint{margin:0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fform-submit{align-self:flex-start;border:0;border-radius:8px;padding:8px 18px;font:inherit;font-weight:600;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}.sv-fform-submit:disabled{opacity:.6;cursor:progress}.sv-fform-failure{font-size:13px}.sv-fform-done{align-items:flex-start}.sv-fform.is-steps{min-height:340px;overflow:hidden}.sv-fform-progress{height:4px;border-radius:999px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 8%,transparent);overflow:hidden}.sv-fform-progress>span{display:block;height:100%;border-radius:inherit;background:var(--sg-accent, #2563eb);transition:width .3s ease}.sv-fform-step{display:flex;flex-direction:column;gap:10px;flex:1}.sv-fform-count{margin:0;font-size:12px;font-weight:600;letter-spacing:.02em;color:var(--sg-accent, #2563eb)}.is-steps .sv-fform-label{font-size:19px;font-weight:600;line-height:1.3}.is-steps .sv-fform-label :global(svg){display:none}.is-steps .sv-fform-hint{font-size:13px}.sv-fform-nav{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.sv-fform-nav .sv-fform-submit{align-self:auto}.sv-fform-back{border:1px solid var(--sg-border, #e2e8f0);border-radius:8px;padding:7px 16px;font:inherit;cursor:pointer;background:transparent;color:inherit}.sv-fform-back:hover{background:color-mix(in srgb,var(--sg-fg, #0f172a) 5%,transparent)}.sv-fform-enter{font-size:12px;color:var(--sg-muted, #64748b)}@media(hover:none){.sv-fform-enter{display:none}}@media(prefers-reduced-motion:reduce){.sv-fform-progress>span{transition:none}}
124
+ .sv-fform-footer{margin-top:16px;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fform-footer p{margin:0 0 6px}.sv-fform-wrap{height:100%;overflow:auto;box-sizing:border-box;padding:24px 16px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 4%,var(--sg-bg, #fff));font-family:var(--sg-font, inherit);color:var(--sg-fg, #0f172a)}.sv-fform{max-width:640px;margin:0 auto;padding:24px 28px;display:flex;flex-direction:column;gap:18px;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #e2e8f0);border-radius:12px}.sv-fform-title{margin:0;font-size:22px}.sv-fform-title:focus-visible{outline:2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb));outline-offset:2px}.sv-fform-desc{margin:-10px 0 0;color:var(--sg-muted, #64748b)}.sv-fform-field{display:flex;flex-direction:column;gap:6px}.sv-fform-label{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600}.sv-fform-req{color:var(--sg-danger, #dc2626)}.sv-fform-field.is-missing :global(.sv-frv-box){border-color:var(--sg-danger, #dc2626)}.sv-fform-error{margin:0;font-size:12px;color:var(--sg-danger, #dc2626)}.sv-fform-hint{margin:0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-fform-suggest{margin-top:-8px;padding:10px 12px;border-radius:8px;background:color-mix(in srgb,var(--sg-accent, #2563eb) 6%,var(--sg-bg, #fff));border:1px solid color-mix(in srgb,var(--sg-accent, #2563eb) 20%,transparent)}.sv-fform-suggest-title{margin:0 0 6px;font-size:12px;font-weight:600;color:var(--sg-muted, #64748b)}.sv-fform-suggest ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:4px}.sv-fform-suggest-item{padding:0;border:0;background:none;font:inherit;font-size:14px;color:var(--sg-accent, #2563eb);text-align:start;cursor:pointer}.sv-fform-suggest-item:hover{text-decoration:underline}.sv-fform-suggest-text{margin:6px 0;font-size:13px;white-space:pre-wrap;max-height:220px;overflow:auto}.sv-fform-solved{border:1px solid var(--sg-border, #e2e8f0);border-radius:6px;padding:4px 10px;font:inherit;font-size:13px;background:var(--sg-bg, #fff);color:inherit;cursor:pointer}.sv-fform-submit{align-self:flex-start;border:0;border-radius:8px;padding:8px 18px;font:inherit;font-weight:600;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}.sv-fform-submit:disabled{opacity:.6;cursor:progress}.sv-fform-failure{font-size:13px}.sv-fform-done{align-items:flex-start}.sv-fform.is-steps{min-height:340px;overflow:hidden}.sv-fform-progress{height:4px;border-radius:999px;background:color-mix(in srgb,var(--sg-fg, #0f172a) 8%,transparent);overflow:hidden}.sv-fform-progress>span{display:block;height:100%;border-radius:inherit;background:var(--sg-accent, #2563eb);transition:width .3s ease}.sv-fform-step{display:flex;flex-direction:column;gap:10px;flex:1}.sv-fform-count{margin:0;font-size:12px;font-weight:600;letter-spacing:.02em;color:var(--sg-accent, #2563eb)}.is-steps .sv-fform-label{font-size:19px;font-weight:600;line-height:1.3}.is-steps .sv-fform-label :global(svg){display:none}.is-steps .sv-fform-hint{font-size:13px}.sv-fform-nav{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.sv-fform-nav .sv-fform-submit{align-self:auto}.sv-fform-back{border:1px solid var(--sg-border, #e2e8f0);border-radius:8px;padding:7px 16px;font:inherit;cursor:pointer;background:transparent;color:inherit}.sv-fform-back:hover{background:color-mix(in srgb,var(--sg-fg, #0f172a) 5%,transparent)}.sv-fform-enter{font-size:12px;color:var(--sg-muted, #64748b)}@media(hover:none){.sv-fform-enter{display:none}}@media(prefers-reduced-motion:reduce){.sv-fform-progress>span{transition:none}}
101
125
  </style>
@@ -12,6 +12,10 @@
12
12
  * answers match it; hidden, it is not checked and not sent. `prefill`
13
13
  * fills fields from a link (`?prefill_<Field name>=value`, form-logic.ts).
14
14
  *
15
+ * With the app's suggestions (setFormSuggestions), the first text field
16
+ * (the subject) brings up to five help articles under it once it holds a
17
+ * few words; "This solved it" on one ends the form unsent.
18
+ *
15
19
  * `layout="steps"` asks one question at a time: a progress bar, Back and
16
20
  * Next (or Enter), each answer checked before the next question, which
17
21
  * slides or fades in (`transition`; none when the visitor asks for less
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{dataRows,fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{barcodeScanSupported,scanBarcode}from"./barcode-scan";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest,closeFieldEditor,getFieldEditorRequest,getDeleteFieldRequest,askDeleteField,openRecord}from"./editor-request.svelte";import FieldEditor from"./FieldEditor.svelte";import DeleteFieldConfirm from"./DeleteFieldConfirm.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights,host=null,tableId}=$props();let barEl=$state(null);$effect(()=>{const el=barEl;const into=host;if(!el||!into)return;const home=document.createComment("");el.before(home);into.appendChild(el);return()=>{if(home.parentNode){home.after(el);home.remove()}else el.remove()}});const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar"||t==="timeline")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="timeline"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));const setSection=(id,section)=>setViews(views.map(v=>{if(v.id!==id)return v;const{section:_was,...rest}=v;return section?{...rest,section:section.slice(0,60)}:rest}));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="timeline"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}return effectiveColor.mode==="conditions"&&effectiveColor.rules.length?bm("viewbar.coloredByConditions"):bm("viewbar.color")});const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const all=ctrl.allRows??[];const trees=all.filter(r=>(r.depth??0)===0&&r.__treeRow);if(trees.length)return trees.reduce((n,r)=>n+(r.treeRecords??1+(r.leafCount??0)),0);const tops=all.filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);const canScan=$derived(quickSearch&&barcodeScanSupported());async function scanToFind(){const code=await scanBarcode();if(!code||!ctrl)return;ctrl.globalFilter=code;searching=true;await tick();await new Promise(r=>setTimeout(r,60));const found=dataRows(ctrl);if(found.length===1)openRecord({ctrl,rowId:found[0].id})}let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="timeline"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldEditing=$derived.by(()=>{const r=getFieldEditorRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldDeleting=$derived.by(()=>{const r=getDeleteFieldRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});$effect(()=>{if(ctrl&&getFieldEditorRequest()?.ctrl===ctrl)untrack(()=>panel=null)});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt"||t==="timeline")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
2
+ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{dataRows,fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{barcodeScanSupported,scanBarcode}from"./barcode-scan";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import{cellRulesOf,setCellRules}from"./cell-colors.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest,closeFieldEditor,getFieldEditorRequest,getDeleteFieldRequest,askDeleteField,openRecord}from"./editor-request.svelte";import FieldEditor from"./FieldEditor.svelte";import DeleteFieldConfirm from"./DeleteFieldConfirm.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights,host=null,tableId}=$props();let barEl=$state(null);$effect(()=>{const el=barEl;const into=host;if(!el||!into)return;const home=document.createComment("");el.before(home);into.appendChild(el);return()=>{if(home.parentNode){home.after(el);home.remove()}else el.remove()}});const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar"||t==="timeline")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="timeline"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));const setSection=(id,section)=>setViews(views.map(v=>{if(v.id!==id)return v;const{section:_was,...rest}=v;return section?{...rest,section:section.slice(0,60)}:rest}));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.cellColors?.length||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor,cellRules]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color,view.cellColors??[]]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color,kept.cellColors??[]]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color,kept.cellColors??[]]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="timeline"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}if(effectiveColor.mode==="conditions"&&effectiveColor.rules.length)return bm("viewbar.coloredByConditions");return cellRules.length?bm("viewbar.coloredCells"):bm("viewbar.color")});const cellRules=$derived(ctrl?cellRulesOf(ctrl):[]);function setCells(next){if(ctrl)setCellRules(ctrl,next)}const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const all=ctrl.allRows??[];const trees=all.filter(r=>(r.depth??0)===0&&r.__treeRow);if(trees.length)return trees.reduce((n,r)=>n+(r.treeRecords??1+(r.leafCount??0)),0);const tops=all.filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);const canScan=$derived(quickSearch&&barcodeScanSupported());async function scanToFind(){const code=await scanBarcode();if(!code||!ctrl)return;ctrl.globalFilter=code;searching=true;await tick();await new Promise(r=>setTimeout(r,60));const found=dataRows(ctrl);if(found.length===1)openRecord({ctrl,rowId:found[0].id})}let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="timeline"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldEditing=$derived.by(()=>{const r=getFieldEditorRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldDeleting=$derived.by(()=>{const r=getDeleteFieldRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});$effect(()=>{if(ctrl&&getFieldEditorRequest()?.ctrl===ctrl)untrack(()=>panel=null)});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt"||t==="timeline")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
3
3
  </script>
4
4
 
5
5
  {#snippet glyph(path: string, size = 15)}
@@ -90,7 +90,7 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
90
90
  {#snippet anchor()}
91
91
  <button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={colorLabel !== bm('viewbar.color')} aria-haspopup="dialog" aria-expanded={panel === 'color'}>{@render glyph(ICON.color)}<span>{colorLabel}</span></button>
92
92
  {/snippet}
93
- <ColorPanel {ctrl} setting={effectiveColor} onChange={setColor} />
93
+ <ColorPanel {ctrl} setting={effectiveColor} onChange={setColor} {cellRules} onCellsChange={setCells} />
94
94
  </SvPopover>
95
95
  {/if}
96
96
  {#if has.has('chart')}
@@ -1,2 +1,2 @@
1
- import{BRIGHT as h}from"./palette.js";import{convertValue as P,countCleared as R}from"./convert.js";import{parseTimeOfDay as v}from"./time-of-day.js";import{blankTable as I,colId as g,newRecordId as N,primaryOf as O}from"./base-tables.js";import{canEditField as k}from"./field-access.svelte.js";import{bm as w}from"./messages.svelte.js";import{splitNames as F}from"./name-list.js";const L=12,U=/^(true|false|yes|no|y|n|x|1|0|checked|unchecked|done|on|off)$/i,H=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,X=/^(https?:\/\/|www\.)\S+$/i,Y=/^\+?[\d\s().-]{7,}$/,z=/^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?/,K=/^\d{1,2}[/.]\d{1,2}[/.]\d{2,4}$/,$=String.raw`(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)`,V=new RegExp(String.raw`^[-+]?${$}(e[-+]?\d+)?$`,"i"),q=new RegExp(String.raw`^[-+]?[$€£¥]\s?${$}$|^[-+]?${$}\s?[$€£¥]$`),G=new RegExp(String.raw`^[-+]?${$}\s?%$`),C=/^([-+]?[$€£¥]?\s?)((?:\d{1,3}(?:[.\s]\d{3})+|\d+)(?:,\d+)?)(\s?[$€£¥%]?)$/,W=/^\d{1,2}:\d{2}(:\d{2})?(\s?[ap]\.?m\.?)?$/i,j=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,J=/^\s*(?:[-*]\s+)?\[( |x|X)?\]\s/;export function commaDecimals(t){const n=t.map(e=>e.trim()).filter(Boolean);return n.length>0&&n.every(e=>C.test(e))&&n.some(e=>/,\d{1,2}(\D*)$|,\d{4,}(\D*)$/.test(e)||/\.\d{3}.*,/.test(e))}function D(t){return t.trim().replace(C,(n,e,o,i)=>`${e}${o.replace(/[.\s]/g,"").replace(",",".")}${i}`)}const Q=new Set(["number","currency","percent","rating","duration","timer"]),_=/^(\d{1,2})([/.-])(\d{1,2})\2(\d{4}|\d{2})(.*)$/;function Z(t){const n=t.map(i=>_.exec(i.trim())).filter(i=>!!i),e=n.some(i=>Number(i[1])>12),o=n.some(i=>Number(i[3])>12);return e===o?null:i=>{const r=_.exec(i.trim());if(!r)return i;const s=r[4].length===2?`20${r[4]}`:r[4],[c,m]=e?[r[3],r[1]]:[r[1],r[3]];return`${s}-${c.padStart(2,"0")}-${m.padStart(2,"0")}${r[5]}`}}function b(t,n){const e=String(n?.fieldType);if(e==="date")return Z(t)??(i=>i);const o=n?.fieldProps?.separators;return Q.has(e)&&(o==="period-comma"||o==="space-comma"||commaDecimals(t))?D:i=>i}export function guessField(t,n){const e=n.map(r=>r.trim()).filter(Boolean);if(!e.length)return{header:t,fieldType:"text"};if(commaDecimals(e))return guessField(t,e.map(D));const o=r=>e.every(s=>r.test(s));if(o(q)){const r=e.map(s=>/[$€£¥]/.exec(s)?.[0]).find(Boolean)??"$";return{header:t,fieldType:"number",fieldProps:{format:"currency",symbol:r,precision:e.some(s=>/\.\d/.test(s))?2:0}}}if(o(G))return{header:t,fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}};if(o(U)&&e.some(r=>!/^[01]$/.test(r)))return{header:t,fieldType:"checkbox"};if(o(V)){const r=e.reduce((s,c)=>Math.max(s,/\.(\d+)$/.exec(c)?.[1]?.length??0),0);return{header:t,fieldType:"number",fieldProps:r?{format:"decimal",precision:Math.min(r,4)}:{format:"integer"}}}if(o(H))return{header:t,fieldType:"email"};if(o(X))return{header:t,fieldType:"url"};if(o(z)||o(K)&&e.every(r=>!Number.isNaN(new Date(r).getTime()))){const r=e.some(s=>/\d{2}:\d{2}/.test(s));return{header:t,fieldType:"date",fieldProps:r?{time:!0}:{}}}if(o(W)&&e.every(r=>v(r)!=null))return{header:t,fieldType:"timeOfDay",fieldProps:e.some(r=>/[ap]\.?m/i.test(r))?{}:{timeFormat:"24hour"}};if(o(j))return{header:t,fieldType:"color"};if(o(J))return{header:t,fieldType:"checklist"};if(o(Y)&&e.every(r=>(r.match(/\d/g)?.length??0)>=7))return{header:t,fieldType:"phone"};if(e.some(r=>r.length>120||r.includes(`
2
- `)))return{header:t,fieldType:"longText"};if(e.some(r=>r.includes(","))){const r=e.flatMap(c=>c.split(",").map(m=>m.trim()).filter(Boolean)),s=[...new Set(r)];return s.length<=L*2&&s.length<r.length/2&&s.every(c=>c.length<=40)?{header:t,fieldType:"multiSelect",fieldProps:{options:x(s)}}:{header:t,fieldType:"text"}}const i=[...new Set(e)];return e.length>=4&&i.length<=L&&i.length<=e.length/2&&i.every(r=>r.length<=40)?{header:t,fieldType:"singleSelect",fieldProps:{options:x(i)}}:{header:t,fieldType:"text"}}const x=t=>t.map((n,e)=>({value:n,color:h[e%h.length].value}));function ee(t,n){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=/^\d/.test(e)?`f_${e}`:e;for(let i=2;n.has(o)||o==="id";i+=1)o=`${e}_${i}`;return n.add(o),o}function E(t){return t.slice(1).filter(n=>n.some(e=>String(e??"").trim()!=="")).map(n=>n.map(e=>String(e??"")))}export function tableFromMatrix(t,n,e,o={}){const i=(t[0]??[]).map((p,f)=>String(p??"").trim()||w("shell.importFieldName",{n:f+1})),r=E(t),s=new Set,c=i.map((p,f)=>{const d=guessField(p,r.map(M=>M[f]??"")),u=ee(p,s),T=f===0&&!o[0]?"text":o[f]??importTypeOf(d),{fieldType:a,fieldProps:S}=T===importTypeOf(d)?d:te(T,r.map(M=>M[f]??""));return{id:u,field:u,header:p,...f===0?{width:220}:{},fieldType:a,...S?{fieldProps:S}:{}}}),m=c.map((p,f)=>b(r.map(d=>d[f]??""),p)),y=r.map(p=>{const f={id:N()};return c.forEach((d,u)=>f[d.field]=P(m[u](p[u]??""),"text",d.fieldType,d.fieldProps)),f}),l=I(n,ne(e,n));return{...l,primaryField:String(c[0]?.field??"name"),columns:c.length?c:l.columns,data:y}}export function importTypeOf(t){const n=t.fieldProps?.format;return t.fieldType==="number"&&(n==="currency"||n==="percent")?n:t.fieldType}function te(t,n){return t==="currency"?{fieldType:"number",fieldProps:{format:"currency",symbol:n.map(o=>/[$€£¥]/.exec(o)?.[0]).find(Boolean)??"$",precision:2}}:t==="percent"?{fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}}:t==="singleSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.map(e=>e.trim()).filter(Boolean))].slice(0,200))}}:t==="multiSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.flatMap(e=>e.split(",").map(o=>o.trim())).filter(Boolean))].slice(0,200))}}:{fieldType:t}}function ne(t,n){const e=new Set(n.map(i=>i.name.toLowerCase()));let o=t.trim()||w("shell.importedName");for(let i=2;e.has(o.toLowerCase());i+=1)o=`${t.trim()||w("shell.importedName")} ${i}`;return o}const re=new Set(["formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button"]),oe=new Set(["text","longText","singleSelect","multiSelect"]);export function importTargets(t){return t.columns.filter(n=>n.field!=null&&n.recordKey!==!0&&!re.has(n.fieldType)&&k(n,n.fieldProps??{})).map(n=>({id:g(n),header:String(n.header??n.field),fieldType:n.fieldType}))}export function withEveryColumn(t){const n=t.reduce((i,r)=>Math.max(i,r.length),0),[e=[],...o]=t;return e.length>=n?t:[[...e,...new Array(n-e.length).fill("")],...o]}export function cellsLost(t,n){return B(t,n,e=>!oe.has(e)&&!A.has(e))}export function cellsUnmatched(t,n){return B(t,n,e=>A.has(e))}const A=new Set(["user","vote","link"]);function B(t,n,e){const o=E(t);let i=0;return n.forEach((r,s)=>{if(!r?.fieldType||!e(r.fieldType))return;const c=o.map(m=>m[s]??"");i+=R(c.map(b(c,r)),"text",r.fieldType,r.fieldProps)}),i}export function repeatedRecords(t,n,e){const o=O(n),i=e.findIndex(s=>s!=null&&(s===o||String(n.columns.find(c=>g(c)===s)?.field)===o));if(i<0)return 0;const r=new Set(n.data.map(s=>String(s[o]??"").trim().toLowerCase()).filter(Boolean));return E(t).filter(s=>r.has(String(s[i]??"").trim().toLowerCase())).length}export function matchColumns(t,n){const e=r=>r.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),o=importTargets(n),i=new Set;return t.map(r=>{const s=e(r),c=o.find(m=>!i.has(m.id)&&(e(m.header)===s||e(m.id)===s));return c&&i.add(c.id),c?.id??null})}export function recordsFromMatrix(t,n,e){const o=E(t),i=new Map(n.columns.map(l=>[g(l),l])),r=n.columns.map(l=>{const p=e.indexOf(g(l));if(p<0||l.fieldType!=="singleSelect"&&l.fieldType!=="multiSelect")return l;const f=l.fieldProps?.options??[],d=new Set(f.flatMap(a=>[a.value,a.label??a.value]).map(a=>String(a).toLowerCase())),u=[...new Set(o.flatMap(a=>l.fieldType==="multiSelect"?F(a[p]??""):[a[p]??""]).map(a=>a.trim()).filter(a=>a&&!d.has(a.toLowerCase())))];if(!u.length)return l;const T=[...f,...u.map((a,S)=>({value:a,color:h[(f.length+S)%h.length].value}))];return{...l,fieldProps:{...l.fieldProps,options:T}}}),s=new Map(r.map(l=>[g(l),l])),c=e.map((l,p)=>b(o.map(f=>f[p]??""),l?s.get(l):void 0)),m=o.map(l=>{const p={id:N()};return e.forEach((f,d)=>{if(!f||!i.has(f))return;const u=s.get(f);p[String(u.field)]=P(c[d](l[d]??""),"text",u.fieldType??"text",u.fieldProps)}),p}),y=O(n);return e.some(l=>l&&String(s.get(l)?.field)===y)||m.forEach((l,p)=>l[y]??(l[y]=w("shell.importedRecordName",{n:p+1}))),{rows:m,columns:r}}
1
+ import{BRIGHT as h}from"./palette.js";import{convertValue as P,countCleared as R}from"./convert.js";import{parseTimeOfDay as v}from"./time-of-day.js";import{blankTable as I,colId as g,newRecordId as N,primaryOf as L}from"./base-tables.js";import{canEditField as k}from"./field-access.svelte.js";import{bm as w}from"./messages.svelte.js";import{splitNames as F}from"./name-list.js";const O=12,U=/^(true|false|yes|no|y|n|x|1|0|checked|unchecked|done|on|off)$/i,H=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,X=/^(https?:\/\/|www\.)\S+$/i,Y=/^\+?[\d\s().-]{7,}$/,K=/^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?/,V=/^\d{1,2}[/.]\d{1,2}[/.]\d{2,4}$/,$=String.raw`(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)`,q=new RegExp(String.raw`^[-+]?${$}(e[-+]?\d+)?$`,"i"),z=new RegExp(String.raw`^[-+]?[$€£¥]\s?${$}$|^[-+]?${$}\s?[$€£¥]$`),G=new RegExp(String.raw`^[-+]?${$}\s?%$`),C=/^([-+]?[$€£¥]?\s?)((?:\d{1,3}(?:[.\s]\d{3})+|\d+)(?:,\d+)?)(\s?[$€£¥%]?)$/,W=/^\d{1,2}:\d{2}(:\d{2})?(\s?[ap]\.?m\.?)?$/i,j=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,J=/^\s*(?:[-*]\s+)?\[( |x|X)?\]\s/;export function commaDecimals(t){const n=t.map(e=>e.trim()).filter(Boolean);return n.length>0&&n.every(e=>C.test(e))&&n.some(e=>/,\d{1,2}(\D*)$|,\d{4,}(\D*)$/.test(e)||/\.\d{3}.*,/.test(e))}function D(t){return t.trim().replace(C,(n,e,o,i)=>`${e}${o.replace(/[.\s]/g,"").replace(",",".")}${i}`)}const Q=new Set(["number","currency","percent","rating","duration","timer"]),_=/^(\d{1,2})([/.-])(\d{1,2})\2(\d{4}|\d{2})(.*)$/;function Z(t){const n=t.map(i=>_.exec(i.trim())).filter(i=>!!i),e=n.some(i=>Number(i[1])>12),o=n.some(i=>Number(i[3])>12);return e===o?null:i=>{const r=_.exec(i.trim());if(!r)return i;const s=r[4].length===2?`20${r[4]}`:r[4],[c,m]=e?[r[3],r[1]]:[r[1],r[3]];return`${s}-${c.padStart(2,"0")}-${m.padStart(2,"0")}${r[5]}`}}function b(t,n){const e=String(n?.fieldType);if(e==="date")return Z(t)??(i=>i);const o=n?.fieldProps?.separators;return Q.has(e)&&(o==="period-comma"||o==="space-comma"||commaDecimals(t))?D:i=>i}export function guessField(t,n){const e=n.map(r=>r.trim()).filter(Boolean);if(!e.length)return{header:t,fieldType:"text"};if(commaDecimals(e))return guessField(t,e.map(D));const o=r=>e.every(s=>r.test(s));if(o(z)){const r=e.map(s=>/[$€£¥]/.exec(s)?.[0]).find(Boolean)??"$";return{header:t,fieldType:"number",fieldProps:{format:"currency",symbol:r,precision:e.some(s=>/\.\d/.test(s))?2:0}}}if(o(G))return{header:t,fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}};if(o(U)&&e.some(r=>!/^[01]$/.test(r)))return{header:t,fieldType:"checkbox"};if(o(q)){const r=e.reduce((s,c)=>Math.max(s,/\.(\d+)$/.exec(c)?.[1]?.length??0),0);return{header:t,fieldType:"number",fieldProps:r?{format:"decimal",precision:Math.min(r,4)}:{format:"integer"}}}if(o(H))return{header:t,fieldType:"email"};if(o(X))return{header:t,fieldType:"url"};if(o(K)||o(V)&&e.every(r=>!Number.isNaN(new Date(r).getTime()))){const r=e.some(s=>/\d{2}:\d{2}/.test(s));return{header:t,fieldType:"date",fieldProps:r?{time:!0}:{}}}if(o(W)&&e.every(r=>v(r)!=null))return{header:t,fieldType:"timeOfDay",fieldProps:e.some(r=>/[ap]\.?m/i.test(r))?{}:{timeFormat:"24hour"}};if(o(j))return{header:t,fieldType:"color"};if(o(J))return{header:t,fieldType:"checklist"};if(o(Y)&&e.every(r=>(r.match(/\d/g)?.length??0)>=7))return{header:t,fieldType:"phone"};if(e.some(r=>r.length>120||r.includes(`
2
+ `)))return{header:t,fieldType:"longText"};if(e.some(r=>r.includes(","))){const r=e.flatMap(c=>c.split(",").map(m=>m.trim()).filter(Boolean)),s=[...new Set(r)];return s.length<=O*2&&s.length<r.length/2&&s.every(c=>c.length<=40)?{header:t,fieldType:"multiSelect",fieldProps:{options:x(s)}}:{header:t,fieldType:"text"}}const i=[...new Set(e)];return e.length>=4&&i.length<=O&&i.length<=e.length/2&&i.every(r=>r.length<=40)?{header:t,fieldType:"singleSelect",fieldProps:{options:x(i)}}:{header:t,fieldType:"text"}}const x=t=>t.map((n,e)=>({value:n,color:h[e%h.length].value}));function ee(t,n){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=/^\d/.test(e)?`f_${e}`:e;for(let i=2;n.has(o)||o==="id";i+=1)o=`${e}_${i}`;return n.add(o),o}function E(t){return t.slice(1).filter(n=>n.some(e=>String(e??"").trim()!=="")).map(n=>n.map(e=>String(e??"")))}export function tableFromMatrix(t,n,e,o={}){const i=(t[0]??[]).map((p,f)=>String(p??"").trim()||w("shell.importFieldName",{n:f+1})),r=E(t),s=new Set,c=i.map((p,f)=>{const d=guessField(p,r.map(M=>M[f]??"")),u=ee(p,s),T=f===0&&!o[0]?"text":o[f]??importTypeOf(d),{fieldType:a,fieldProps:S}=T===importTypeOf(d)?d:te(T,r.map(M=>M[f]??""));return{id:u,field:u,header:p,...f===0?{width:220}:{},fieldType:a,...S?{fieldProps:S}:{}}}),m=c.map((p,f)=>b(r.map(d=>d[f]??""),p)),y=r.map(p=>{const f={id:N()};return c.forEach((d,u)=>f[d.field]=P(m[u](p[u]??""),"text",d.fieldType,d.fieldProps)),f}),l=I(n,ne(e,n));return{...l,primaryField:String(c[0]?.field??"name"),columns:c.length?c:l.columns,data:y}}export function importTypeOf(t){const n=t.fieldProps?.format;return t.fieldType==="number"&&(n==="currency"||n==="percent")?n:t.fieldType}function te(t,n){return t==="currency"?{fieldType:"number",fieldProps:{format:"currency",symbol:n.map(o=>/[$€£¥]/.exec(o)?.[0]).find(Boolean)??"$",precision:2}}:t==="percent"?{fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}}:t==="singleSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.map(e=>e.trim()).filter(Boolean))].slice(0,200))}}:t==="multiSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.flatMap(e=>e.split(",").map(o=>o.trim())).filter(Boolean))].slice(0,200))}}:{fieldType:t}}function ne(t,n){const e=new Set(n.map(i=>i.name.toLowerCase()));let o=t.trim()||w("shell.importedName");for(let i=2;e.has(o.toLowerCase());i+=1)o=`${t.trim()||w("shell.importedName")} ${i}`;return o}const re=new Set(["formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button"]),oe=new Set(["text","longText","singleSelect","multiSelect"]);export function importTargets(t){return t.columns.filter(n=>n.field!=null&&n.recordKey!==!0&&!re.has(n.fieldType)&&k(n,n.fieldProps??{})).map(n=>({id:g(n),header:String(n.header??n.field),fieldType:n.fieldType}))}export function withEveryColumn(t){const n=t.reduce((i,r)=>Math.max(i,r.length),0),[e=[],...o]=t;return e.length>=n?t:[[...e,...new Array(n-e.length).fill("")],...o]}export function cellsLost(t,n){return B(t,n,e=>!oe.has(e)&&!A.has(e))}export function cellsUnmatched(t,n){return B(t,n,e=>A.has(e))}const A=new Set(["user","vote","link"]);function B(t,n,e){const o=E(t);let i=0;return n.forEach((r,s)=>{if(!r?.fieldType||!e(r.fieldType))return;const c=o.map(m=>m[s]??"");i+=R(c.map(b(c,r)),"text",r.fieldType,r.fieldProps)}),i}export function repeatedRecords(t,n,e){const o=L(n),i=e.findIndex(s=>s!=null&&(s===o||String(n.columns.find(c=>g(c)===s)?.field)===o));if(i<0)return 0;const r=new Set(n.data.map(s=>String(s[o]??"").trim().toLowerCase()).filter(Boolean));return E(t).filter(s=>r.has(String(s[i]??"").trim().toLowerCase())).length}export function matchColumns(t,n){const e=r=>r.trim().toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),o=importTargets(n),i=new Set;return t.map(r=>{const s=e(r),c=s?o.find(m=>!i.has(m.id)&&(e(m.header)===s||e(m.id)===s)):void 0;return c&&i.add(c.id),c?.id??null})}export function recordsFromMatrix(t,n,e){const o=E(t),i=new Map(n.columns.map(l=>[g(l),l])),r=n.columns.map(l=>{const p=e.indexOf(g(l));if(p<0||l.fieldType!=="singleSelect"&&l.fieldType!=="multiSelect")return l;const f=l.fieldProps?.options??[],d=new Set(f.flatMap(a=>[a.value,a.label??a.value]).map(a=>String(a).toLowerCase())),u=[...new Set(o.flatMap(a=>l.fieldType==="multiSelect"?F(a[p]??""):[a[p]??""]).map(a=>a.trim()).filter(a=>a&&!d.has(a.toLowerCase())))];if(!u.length)return l;const T=[...f,...u.map((a,S)=>({value:a,color:h[(f.length+S)%h.length].value}))];return{...l,fieldProps:{...l.fieldProps,options:T}}}),s=new Map(r.map(l=>[g(l),l])),c=e.map((l,p)=>b(o.map(f=>f[p]??""),l?s.get(l):void 0)),m=o.map(l=>{const p={id:N()};return e.forEach((f,d)=>{if(!f||!i.has(f))return;const u=s.get(f);p[String(u.field)]=P(c[d](l[d]??""),"text",u.fieldType??"text",u.fieldProps)}),p}),y=L(n);return e.some(l=>l&&String(s.get(l)?.field)===y)||m.forEach((l,p)=>l[y]??(l[y]=w("shell.importedRecordName",{n:p+1}))),{rows:m,columns:r}}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A small celebration when someone finishes something: a burst of fireworks
3
+ * where they did it, for a moment, when one record turns done. "Done" is a
4
+ * single select set to an option such as Done, Completed, Shipped, Paid or Won
5
+ * (Готово, Завършено, Платено), or a checkbox field with such a name ticked.
6
+ * A field opts out with `fieldProps.celebrate: false`, or in with `true`
7
+ * (any option or tick then counts).
8
+ *
9
+ * Off unless SvBase's `celebrate` prop is on. Never for an undo or redo, a
10
+ * paste or fill of several cells, or a page whose reader asks the system for
11
+ * less motion; at most once every two seconds. The canvas lies over the page
12
+ * without taking clicks, and is gone when the sparks are.
13
+ */
14
+ type Def = Record<string, any>;
15
+ /** Whether `value` is "done" in this field. */
16
+ export declare function isDone(def: Def | undefined, value: unknown): boolean;
17
+ /** Whether a change turned this field done: it was not, and now is. */
18
+ export declare const becameDone: (def: Def | undefined, before: unknown, after: unknown) => boolean;
19
+ /**
20
+ * A cell changed (SvBase's onCellValueChange). Every change of this moment is
21
+ * counted; when only one was made and it turned a record done, the sparks fly.
22
+ */
23
+ export declare function noteChange(ctrl: any, def: Def | undefined, before: unknown, after: unknown, row?: unknown, columnId?: string): void;
24
+ /** Three bursts above `at`, about a second and a half, then the canvas goes. */
25
+ export declare function fireworks(at: {
26
+ x: number;
27
+ y: number;
28
+ }): void;
29
+ export {};
@@ -0,0 +1 @@
1
+ const M=/^(done|complete|completed|finished|closed|resolved|shipped|delivered|paid|won|approved|published|live|fixed|готово|завършен[оаи]?|приключен[оаи]?|платен[оаи]?|доставен[оаи]?|одобрен[оаи]?|спечелен[оаи]?|решен[оаи]?|изпратен[оаи]?|erledigt|fertig|terminé|hecho|completato)$/iu,E=e=>e&&typeof e=="object"?String(e.name??e.value??""):e==null?"":String(e),P=e=>e===!0||e===1||e==="true";export function isDone(e,t){if(!e)return!1;const i=e.fieldProps?.celebrate;if(i===!1)return!1;if(e.fieldType==="checkbox")return P(t)&&(i===!0||M.test(String(e.header??"").trim()));if(e.fieldType==="singleSelect"){const r=E(t).trim();return!!r&&(i===!0||M.test(r))}return!1}export const becameDone=(e,t,i)=>isDone(e,i)&&!isDone(e,t);let m=null,S=!1,v=0,c=null;function $(){if(S||typeof window>"u")return;S=!0;const e=t=>m={x:t.clientX,y:t.clientY,at:Date.now()};window.addEventListener("pointerdown",e,!0),window.addEventListener("pointerup",e,!0)}const k=()=>typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;$();const C=e=>e&&e.width?{x:e.left+e.width/2,y:e.top+e.height/2}:null;function T(e,t,i){const r=e?.gridRootEl;let s=null;try{const o=t!=null?e?.props?.getRowId?.(t,0):void 0;s=o==null?null:String(o)}catch{s=null}const a=t!=null&&i?(e?.allRows??[]).findIndex(o=>o.original===t||s!=null&&o.id===s):-1;if(r&&a>=0){const l=r.querySelector(`[data-svgrid-row="${a}"][data-col-id="${typeof CSS<"u"&&CSS.escape?CSS.escape(String(i)):String(i).replace(/["\\]/g,"\\$&")}"]`)?.getBoundingClientRect();if(l&&l.width&&l.bottom>0&&l.top<innerHeight&&l.right>0&&l.left<innerWidth)return C(l)}return m&&Date.now()-m.at<2500?m:C(r?.getBoundingClientRect())??{x:(typeof innerWidth=="number"?innerWidth:800)/2,y:(typeof innerHeight=="number"?innerHeight:600)/2}}export function noteChange(e,t,i,r,s,a){e?.props?.celebrate&&(c||(c={changes:0,done:[]},setTimeout(()=>{const o=c;if(c=null,o.changes!==1||o.done.length!==1||k())return;const l=Date.now();l-v<2e3||(v=l,fireworks(o.done[0]))},0)),c.changes+=1,becameDone(t,i,r)&&c.done.push(T(e,s,a)))}const R=["#fcb400","#f82b60","#20c933","#2d7ff9","#8b46ff","#18bfff","#ff6f2c"];export function fireworks(e){if(typeof document>"u")return;const t=document.createElement("canvas"),i=t.getContext?.("2d");if(!i)return;const r=Math.min(2,window.devicePixelRatio||1),s=window.innerWidth,a=window.innerHeight;t.width=s*r,t.height=a*r,t.setAttribute("aria-hidden","true"),t.className="sv-celebrate",Object.assign(t.style,{position:"fixed",inset:"0",width:`${s}px`,height:`${a}px`,pointerEvents:"none",zIndex:"2147483000"}),document.body.appendChild(t),i.scale(r,r);const o=[],l=(w,x,n)=>{for(let f=0;f<n;f++){const p=Math.PI*2*f/n+Math.random()*.3,b=2.2+Math.random()*3.2;o.push({x:w,y:x,vx:Math.cos(p)*b,vy:Math.sin(p)*b-1,life:1,color:R[Math.random()*R.length|0],size:1.6+Math.random()*1.8})}},h=Math.max(40,Math.min(s-40,e.x)),g=Math.max(60,Math.min(a-20,e.y)),u=[[0,h,g-10,46],[180,h-70,g-70,34],[340,h+80,g-55,34]],D=performance.now();let d=0;const y=w=>{const x=w-D;for(;d<u.length&&x>=u[d][0];){const[,n,f,p]=u[d];l(Math.max(20,Math.min(s-20,n)),Math.max(20,f),p),d++}i.clearRect(0,0,s,a);for(const n of o)n.vy+=.07,n.vx*=.985,n.vy*=.985,n.x+=n.vx,n.y+=n.vy,n.life-=.016,!(n.life<=0)&&(i.globalAlpha=Math.max(0,n.life),i.fillStyle=n.color,i.beginPath(),i.arc(n.x,n.y,n.size,0,Math.PI*2),i.fill());d<u.length||o.some(n=>n.life>0)?requestAnimationFrame(y):t.remove()};requestAnimationFrame(y),setTimeout(()=>t.remove(),4e3)}
@@ -0,0 +1,17 @@
1
+ import { type FieldCondition, type LinkNames } from './filter-model.js';
2
+ export type CellColorRule = {
3
+ color: string;
4
+ condition: FieldCondition;
5
+ };
6
+ /** The cell rules this grid's view shows. */
7
+ export declare function cellRulesOf(ctrl: unknown): CellColorRule[];
8
+ /** Show these cell rules on this grid (an empty list: none). */
9
+ export declare function setCellRules(ctrl: unknown, rules: ReadonlyArray<CellColorRule>): void;
10
+ /** A tint of the rule's color behind the cell: the text stays readable in a light or dark theme. */
11
+ export declare const cellTint: (color: string) => string;
12
+ /**
13
+ * The grid's `conditionalFormats` for the rules: one per rule, on the field it
14
+ * tests, drawn while it matches and no earlier rule of that field does. A rule on
15
+ * a field the grid no longer has, or not finished yet, draws nothing.
16
+ */
17
+ export declare function cellColorFormats(ctrl: unknown, rules: ReadonlyArray<CellColorRule>, linkNames?: LinkNames): unknown[];
@@ -0,0 +1 @@
1
+ import{fieldColumns}from"./grid-access.js";import{safeColor}from"./palette.js";import{compileFieldFilter}from"./filter-model.js";const chosen=new WeakMap;let version=$state(0);export function cellRulesOf(ctrl){void version;return(ctrl&&typeof ctrl==="object"?chosen.get(ctrl):void 0)??[]}export function setCellRules(ctrl,rules){if(!ctrl||typeof ctrl!=="object")return;chosen.set(ctrl,rules.map(r=>({color:r.color,condition:{...r.condition}})));version+=1}export const cellTint=color=>`color-mix(in srgb, ${safeColor(color)??"#fcb400"} 30%, transparent)`;export function cellColorFormats(ctrl,rules,linkNames){if(!rules.length)return[];const cols=new Map(fieldColumns(ctrl).map(c=>[c.id,c]));const valueOf=(row,id)=>{const col=cols.get(id);if(!col)return void 0;const fn=col.def.fieldFn;return fn?fn(row):row?.[col.field]};const tests=rules.map(r=>{if(!cols.has(r.condition.column))return null;const test=compileFieldFilter({kind:"fieldFilter",conjunction:"and",conditions:[r.condition]},valueOf,linkNames);return test?{column:r.condition.column,color:r.color,test}:null});const safe=(test,row)=>{try{return test(row)}catch{return false}};const out=[];tests.forEach((t,i)=>{if(!t)return;const earlier=tests.slice(0,i).filter(e=>!!e&&e.column===t.column);out.push({type:"rule",columns:[t.column],when:({row})=>safe(t.test,row)&&!earlier.some(e=>safe(e.test,row)),background:cellTint(t.color)})});return out}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Saved replies in a record's comment box (a service desk's "canned
3
+ * responses"). The app lists them per table and record, already filled in
4
+ * from the record ("Hi Ana, ..."), and may keep a new one from the text being
5
+ * written. Picking one puts its text in the box, with its files, to change
6
+ * before sending; nothing is sent by picking.
7
+ *
8
+ * setCommentSnippets({
9
+ * list: async (tableId, { rowId, row }) => [{ id: 'r1', title: 'Invoice received', text: 'Hi Ana, ...' }],
10
+ * save: async (tableId, { title, text }) => { ... }, // optional: "Save this text as a reply"
11
+ * })
12
+ *
13
+ * Without it the comment box has no "Saved replies".
14
+ */
15
+ import type { Attachment } from './attachments.js';
16
+ import type { RecordActionRecord } from './record-actions.js';
17
+ export type CommentSnippet = {
18
+ id: string;
19
+ title: string;
20
+ text: string;
21
+ files?: Attachment[];
22
+ };
23
+ export type CommentSnippets = {
24
+ /** The replies for this record, filled in from it. */
25
+ list: (tableId: string | undefined, record: RecordActionRecord) => CommentSnippet[] | Promise<CommentSnippet[]>;
26
+ /** Keep the text being written as a new reply. Without it, the box offers no "Save". */
27
+ save?: (tableId: string | undefined, reply: {
28
+ title: string;
29
+ text: string;
30
+ }) => void | Promise<void>;
31
+ };
32
+ /** The app's saved replies, or `null` for none. */
33
+ export declare function setCommentSnippets(snippets: CommentSnippets | null): void;
34
+ /** The saved replies set, read reactively by the record view. */
35
+ export declare function commentSnippets(): CommentSnippets | null;
@@ -0,0 +1 @@
1
+ let store=$state.raw(null);export function setCommentSnippets(snippets){store=snippets}export function commentSnippets(){return store}
@@ -5,6 +5,13 @@ export type FieldEditorRequest = {
5
5
  columnId?: string;
6
6
  /** Where a new field goes (mode 'add'). */
7
7
  index?: number | 'end';
8
+ /** What a new field starts as (mode 'add'): its type, and properties such as a formula. */
9
+ preset?: FieldPreset;
10
+ };
11
+ export type FieldPreset = {
12
+ fieldType: string;
13
+ name?: string;
14
+ fieldProps?: Record<string, unknown>;
8
15
  };
9
16
  export declare const getFieldEditorRequest: () => FieldEditorRequest | null;
10
17
  export declare function openFieldEditor(r: FieldEditorRequest): void;
@@ -0,0 +1,98 @@
1
+ import { type ImportedField } from './base-import.js';
2
+ type Ctrl = any;
3
+ /** A grid SvBase drew: these hints are a base's, not a plain grid's. */
4
+ export declare const isBaseGrid: (ctrl: Ctrl) => boolean;
5
+ /** What a sheet's formula is in a base: a formula field's, or a summary of one field. */
6
+ export type SheetFormula = {
7
+ formula: string;
8
+ } | {
9
+ summary: {
10
+ columnId: string;
11
+ kind: 'sum' | 'avg' | 'min' | 'max' | 'median' | 'filled';
12
+ };
13
+ } | null;
14
+ /**
15
+ * A sheet's formula as a base's. `fields` are the names of the shown fields,
16
+ * column A first; `row` is the row the formula was typed on, counted from 1.
17
+ * References on that row become `{Field}` references. A function of one
18
+ * column's run of rows (`=SUM(C2:C9)`) is that field's summary. Anything else
19
+ * reaching other rows has no formula field like it: null.
20
+ */
21
+ export declare function sheetFormula(text: string, fields: ReadonlyArray<{
22
+ id: string;
23
+ header: string;
24
+ }>, row: number): SheetFormula;
25
+ /** Whether text typed in a cell is a sheet's formula: "=" and something after it. */
26
+ export declare const looksLikeFormula: (value: unknown) => value is string;
27
+ /**
28
+ * A formula was typed in a cell of a field that is not a formula: the base says
29
+ * where formulas go, with a button that makes one from it. `rowIndex` is the
30
+ * row it was typed on; `columnId` the field.
31
+ */
32
+ export declare function formulaTyped(api: unknown, columnId: string, text: string, rowIndex: number): void;
33
+ /**
34
+ * Alt+= in a base: a sheet's AutoSum writes `=SUM(B1:B9)` into the cell, which
35
+ * a base has no use for. Here the field's sum goes in the summary bar instead,
36
+ * where it keeps up as records change. Registered above the sheet keymap.
37
+ */
38
+ export declare function autoSumKey(e: KeyboardEvent, cmd: {
39
+ api: unknown;
40
+ editing: boolean;
41
+ activeCell?: {
42
+ colIndex: number;
43
+ } | null;
44
+ }): boolean;
45
+ /**
46
+ * A sheet's formatting keys in a base: bold, italic, underline, Format Cells. A
47
+ * base keeps no formatting typed into a cell, so every screen reads the same
48
+ * data; color comes from rules in the view bar's Color. Said once per grid, with
49
+ * a button that opens Color. The key does nothing else.
50
+ */
51
+ export declare function formatKey(e: KeyboardEvent, cmd: {
52
+ api: unknown;
53
+ editing: boolean;
54
+ }): boolean;
55
+ /**
56
+ * A record's name typed as "Total": a sheet's totals row. Said once per grid:
57
+ * the summary bar adds up the number fields, with a button that turns it on.
58
+ */
59
+ export declare function totalTyped(api: unknown, columnId: string, value: unknown): void;
60
+ export type PastePlan = {
61
+ /** The first line is the names of the fields it lands on. */
62
+ named: boolean;
63
+ /** The first line could be names for the fields to add. */
64
+ namesLikely: boolean;
65
+ /** Where the paste starts, among the shown columns. */
66
+ startCol: number;
67
+ /** How many columns of the paste land on a field. */
68
+ room: number;
69
+ /** How many columns have no field to land on. */
70
+ extra: number;
71
+ lines: string[][];
72
+ };
73
+ /**
74
+ * What a paste's shape asks of the base, or null when it lands as it is: a
75
+ * first line that is the fields' names, and columns past the last field.
76
+ */
77
+ export declare function pastePlan(ctrl: Ctrl, lines: string[][]): PastePlan | null;
78
+ /** The fields a paste would add, named from its first line or numbered, typed from their values. */
79
+ export declare function fieldsToAdd(ctrl: Ctrl, plan: PastePlan, namesFromFirst: boolean): ImportedField[];
80
+ export type PasteQuestion = {
81
+ ctrl: Ctrl;
82
+ plan: PastePlan;
83
+ text: string;
84
+ };
85
+ export declare const pasteQuestion: () => PasteQuestion | null;
86
+ export declare const endPasteQuestion: () => void;
87
+ /** The lines to paste now, set by `pasteAgain`, once. */
88
+ export declare function takeReplay(ctrl: Ctrl): string[][] | undefined;
89
+ /** Paste these lines at the selection: the grid's own paste, so it is one undo step and new rows become records. */
90
+ export declare function pasteAgain(ctrl: Ctrl, text: string, lines: string[][]): void;
91
+ /**
92
+ * The lines a paste writes, once the base has looked at its shape. A first line
93
+ * that is the fields' names is left out, and said. Columns with no field to go
94
+ * in: whoever may add fields is asked (the paste waits, and nothing is written
95
+ * now: `[]`); anyone else gets what fits, and is told what was left out.
96
+ */
97
+ export declare function shapePaste(ctrl: Ctrl, lines: string[][], text: string): string[][];
98
+ export {};
@@ -0,0 +1 @@
1
+ import{toast}from"@svgrid/grid";import{bm,bmCount}from"./messages.svelte.js";import{fieldColumns,gridOf,primaryIdOf}from"./grid-access.js";import{openFieldEditor}from"./editor-request.svelte.js";import{nameTaken,setFieldSummary}from"./field-ops.js";import{summaryChoices}from"./summaries.js";import{guessField}from"./base-import.js";import{hasBar,openBarPanel}from"./bar-request.svelte.js";export const isBaseGrid=ctrl=>ctrl?.props?.baseTableId!=null;function shownFields(ctrl){return(ctrl?.allColumns??[]).filter(c=>c.columnDef?.field!=null&&c.columnDef?.fieldType!=null)}const SUMMARY_OF={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",MEDIAN:"median",COUNT:"filled",COUNTA:"filled"};const letterIndex=letters=>[...letters.toUpperCase()].reduce((n,c)=>n*26+(c.charCodeAt(0)-64),0)-1;export function sheetFormula(text,fields,row){const src=text.trim().replace(/^=+/,"").trim();if(!src)return null;const whole=/^([A-Za-z]+)\(\s*\$?([A-Za-z]{1,3})\$?(\d+)\s*:\s*\$?([A-Za-z]{1,3})\$?(\d+)\s*\)$/.exec(src);if(whole){const[,fn,c1,r1,c2,r2]=whole;const kind=SUMMARY_OF[fn.toUpperCase()];const col=letterIndex(c1);if(kind&&col===letterIndex(c2)&&r1!==r2&&fields[col])return{summary:{columnId:fields[col].id,kind}}}const ref=letters=>{const f=fields[letterIndex(letters)];return f?`{${f.header}}`:null};let out="";let other=false;let i=0;while(i<src.length){const c=src[i];if(c==='"'){const end=src.indexOf('"',i+1);const stop=end<0?src.length:end+1;out+=src.slice(i,stop);i=stop;continue}if(c===";"){out+=",";i++;continue}const at=/^\$?([A-Za-z]{1,3})\$?(\d+)(?:\s*:\s*\$?([A-Za-z]{1,3})\$?(\d+))?/.exec(src.slice(i));const before=i>0?src[i-1]:"";if(at&&!/[A-Za-z0-9_.{]/.test(before)&&src[i+at[0].length]!=="("){const[all,c1,r1,c2,r2]=at;if(c2==null){const name=ref(c1);if(!name||Number(r1)!==row)other=true;out+=name??all}else{if(r1!==r2||Number(r1)!==row)other=true;const from=Math.min(letterIndex(c1),letterIndex(c2));const to=Math.max(letterIndex(c1),letterIndex(c2));const names=Array.from({length:to-from+1},(_,k)=>fields[from+k]).map(f=>f?`{${f.header}}`:null);if(names.some(n=>n==null))other=true;out+=names.join(", ")}i+=all.length;continue}out+=c;i++}return other?null:{formula:out}}export const looksLikeFormula=value=>typeof value==="string"&&/^=\s*[^=\s]/.test(value.trim());function showSummary(ctrl,columnId,kind){if(!ctrl?.props?.summary)return false;setFieldSummary(ctrl,columnId,kind);return true}const headerOf=(ctrl,columnId)=>fieldColumns(ctrl).find(c=>c.id===columnId)?.header??columnId;export function formulaTyped(api,columnId,text,rowIndex){const ctrl=gridOf(api)??api;if(!isBaseGrid(ctrl))return;const fields=shownFields(ctrl).map(c=>({id:c.id,header:String(c.columnDef.header??c.id)}));const read=sheetFormula(text,fields,rowIndex+1);if(read&&"summary"in read&&ctrl.props.summary){const{columnId:target,kind}=read.summary;const field=headerOf(ctrl,target);toast(bm("shell.formulaIsSummary",{field}),{action:{label:bm("shell.formulaShowSummary",{field}),onClick:()=>void showSummary(ctrl,target,kind)}});return}if(ctrl.props.columnAdder===false){toast(bm("shell.formulaInField"));return}const at=shownFields(ctrl).findIndex(c=>c.id===columnId);const index=ctrl.internalColumns.findIndex(d=>String(d.id??d.field)===columnId);const formula=read&&"formula"in read?read.formula:"";toast(bm("shell.formulaInField"),{action:{label:bm("shell.formulaMakeField"),onClick:()=>openFieldEditor({ctrl,mode:"add",index:index>=0?index+1:at>=0?at+1:"end",preset:{fieldType:"formula",fieldProps:{formula}}})}})}const summable=def=>summaryChoices(def).some(c=>c.value==="sum");export function autoSumKey(e,cmd){if(e.key!=="="||!e.altKey||e.ctrlKey||e.metaKey||cmd.editing)return false;const ctrl=gridOf(cmd.api);if(!isBaseGrid(ctrl))return false;const column=ctrl.allColumns[cmd.activeCell?.colIndex??ctrl.activeCell?.colIndex??-1];if(!column?.columnDef?.fieldType)return false;const field=String(column.columnDef.header??column.id);e.preventDefault();if(!summable(column.columnDef))toast(bm("shell.sumNotNumbers",{field}));else if(showSummary(ctrl,column.id,"sum"))toast(bm("shell.sumShown",{field}));else toast(bm("shell.sumNoBar"));return true}const FORMAT_KEYS=new Set(["b","i","u","1"]);const toldFormat=new WeakSet;export function formatKey(e,cmd){if(cmd.editing||!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||!FORMAT_KEYS.has(e.key.toLowerCase()))return false;const ctrl=gridOf(cmd.api);if(!isBaseGrid(ctrl))return false;e.preventDefault();if(toldFormat.has(ctrl))return true;toldFormat.add(ctrl);toast(bm("shell.formatInBase"),hasBar(ctrl)?{action:{label:bm("shell.formatOpenColor"),onClick:()=>openBarPanel(ctrl,"color")}}:void 0);return true}const TOTAL=/^(grand\s+)?(total|totals|sub\s*total|sum|общо|сума|всичко|итого|gesamt|summe|totale)\s*:?$/iu;const toldTotal=new WeakSet;export function totalTyped(api,columnId,value){const ctrl=gridOf(api)??api;if(!isBaseGrid(ctrl)||typeof value!=="string"||!TOTAL.test(value.trim()))return;if(columnId!==primaryIdOf(ctrl)||!ctrl.props.summary||toldTotal.has(ctrl))return;const numbers=shownFields(ctrl).filter(c=>summable(c.columnDef));if(!numbers.length)return;toldTotal.add(ctrl);toast(bm("shell.totalRecord"),{action:{label:bm("shell.totalShowSums"),onClick:()=>{for(const c of numbers)if(!c.columnDef.fieldProps?.summary)setFieldSummary(ctrl,c.id,"sum")}}})}const key=s=>s.trim().toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,"");const NUMBERISH=/^[\s$€£¥+\-−(]*\d[\d\s.,]*(%|[kmb])?\)?\s*(лв\.?|€|\$)?$/iu;function startColumn(ctrl){const anchor=ctrl.selectionRange?.anchor??ctrl.activeCell;const focus=ctrl.selectionRange?.focus??anchor;if(!anchor)return-1;return Math.min(anchor.colIndex,focus?.colIndex??anchor.colIndex)}export function pastePlan(ctrl,lines){if(!isBaseGrid(ctrl)||!lines.length||lines.length===1&&(lines[0]?.length??0)<=1)return null;const startCol=startColumn(ctrl);if(startCol<0)return null;const columns=ctrl.allColumns;const width=lines.reduce((n,l)=>Math.max(n,l.length),0);const room=Math.max(0,Math.min(width,columns.length-startCol));const first=lines[0]??[];let same=0;let differ=0;for(let j=0;j<room;j++){const cell=key(first[j]??"");if(!cell)continue;const header=key(String(columns[startCol+j]?.columnDef?.header??""));if(header&&cell===header)same++;else differ++}const named=lines.length>1&&same>0&&differ===0;const extra=width-room;if(!named&&extra<=0)return null;const filled=first.filter(c=>c.trim());const namesLikely=named||lines.length>1&&filled.length===first.length&&filled.every(c=>!NUMBERISH.test(c))&&lines.slice(1).some(l=>l.some((c,j)=>NUMBERISH.test(c)&&!NUMBERISH.test(first[j]??"")));return{named,namesLikely,startCol,room,extra:Math.max(0,extra),lines}}export function fieldsToAdd(ctrl,plan,namesFromFirst){const body=namesFromFirst?plan.lines.slice(1):plan.lines;const taken=new Set;const free=name=>!nameTaken(ctrl,name)&&!taken.has(name.toLowerCase());return Array.from({length:plan.extra},(_,k)=>{const j=plan.room+k;const base=(namesFromFirst?(plan.lines[0]?.[j]??"").trim():"")||`${bm("fields.fallbackName")} ${plan.startCol+j+1}`;let name=base;for(let n=2;!free(name);n++)name=`${base} ${n}`;taken.add(name.toLowerCase());return guessField(name,body.map(l=>l[j]??""))})}let question=$state.raw(null);export const pasteQuestion=()=>question;export const endPasteQuestion=()=>void(question=null);const replays=new WeakMap;export function takeReplay(ctrl){const lines=ctrl?replays.get(ctrl):void 0;if(lines)replays.delete(ctrl);return lines}export function pasteAgain(ctrl,text,lines){replays.set(ctrl,lines);ctrl.pasteText(text);replays.delete(ctrl)}export function shapePaste(ctrl,lines,text){const plan=pastePlan(ctrl,lines);if(!plan)return lines;const body=plan.named?lines.slice(1):lines;if(plan.extra>0&&ctrl.props.columnAdder!==false&&ctrl.props.editable!==false){question={ctrl,plan,text};return[]}if(plan.extra>0)toast(bmCount("shell.pasteNoField",plan.extra));else toast(bm("shell.pasteNamesLeftOut"));return body}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Suggestions on a form, before it is sent: a service desk's help articles
3
+ * that may already answer what is being asked. When the form's first text
4
+ * field (its subject) holds a few words, the app is asked for up to five
5
+ * matches; each opens in place, and "This solved it" tells the app and ends
6
+ * the form without sending anything.
7
+ *
8
+ * setFormSuggestions({
9
+ * list: async (tableId, text, values) => [{ id: 'a1', title: 'Reset your password', text: 'Open Settings, ...' }],
10
+ * solved: (tableId, id) => { ... }, // optional: count what saved a request
11
+ * })
12
+ *
13
+ * Without it, forms suggest nothing.
14
+ */
15
+ export type FormSuggestion = {
16
+ id: string;
17
+ title: string;
18
+ text: string;
19
+ };
20
+ export type FormSuggestions = {
21
+ /** Up to five matches for what the subject says; `values` are the form's answers so far. */
22
+ list: (tableId: string | undefined, text: string, values: Record<string, unknown>) => FormSuggestion[] | Promise<FormSuggestion[]>;
23
+ /** "This solved it" on one of them: the form ends unsent. */
24
+ solved?: (tableId: string | undefined, id: string) => void | Promise<void>;
25
+ };
26
+ /** The app's suggestions for forms, or `null` for none. */
27
+ export declare function setFormSuggestions(suggestions: FormSuggestions | null): void;
28
+ /** The suggestions set, read reactively by the form. */
29
+ export declare function formSuggestions(): FormSuggestions | null;
@@ -0,0 +1 @@
1
+ let store=$state.raw(null);export function setFormSuggestions(suggestions){store=suggestions}export function formSuggestions(){return store}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A short reference for every function a formula field can call, for the
3
+ * editor's autocomplete and its function list. Each entry says how the
4
+ * function is called, what it gives in one plain sentence, and one example
5
+ * with the kind of fields a small business has. The text follows what
6
+ * formula.ts does, not what a spreadsheet does where the two differ.
7
+ */
8
+ export type FormulaDocGroup = 'logic' | 'text' | 'numbers' | 'dates' | 'lists' | 'records';
9
+ export type FormulaDoc = {
10
+ /** How it is called, Excel style: IF(condition, value if true, value if false). Optional arguments in [square brackets]. */
11
+ syntax: string;
12
+ /** One plain sentence, at most about 90 characters, saying what it gives. */
13
+ summary: string;
14
+ /** One example using realistic {Field} names of a small business (Qty, Unit price, Status, Due date, Client, Email...), commas between arguments. */
15
+ example: string;
16
+ group: FormulaDocGroup;
17
+ };
18
+ export declare const FORMULA_DOCS: Record<string, FormulaDoc>;
19
+ /**
20
+ * The argument names of a syntax, for showing which one the caret is in:
21
+ * 'IF(condition, value if true, value if false)' -> ['condition', 'value if true', 'value if false'].
22
+ * Square brackets are dropped and "..." is not a name: 'SUM(number1, [number2, ...])' -> ['number1', 'number2'].
23
+ */
24
+ export declare function syntaxArgs(syntax: string): string[];