@svgrid/enterprise 3.1.34 → 3.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ExpressionEditorHarness.svelte +1 -1
- package/dist/SvAdvancedFilter.svelte +1 -1
- package/dist/SvAlertRuleEditor.svelte +1 -1
- package/dist/SvAlertsManager.svelte +1 -1
- package/dist/SvAlertsPanel.svelte +1 -1
- package/dist/SvExpressionEditor.svelte +1 -1
- package/dist/SvGridBoard.svelte +1 -1
- package/dist/SvGridBulkEditDrawer.svelte +1 -1
- package/dist/SvGridEditPanel.svelte +1 -1
- package/dist/SvGridGallery.svelte +1 -1
- package/dist/SvGridMasterDetail.svelte +1 -1
- package/dist/SvGridScheduler.svelte +1 -1
- package/dist/SvGridSelectionBar.svelte +1 -1
- package/dist/SvPivotDesigner.svelte +1 -1
- package/dist/SvSchemaChart.svelte +1 -1
- package/dist/SvSchemaDashboard.svelte +1 -1
- package/dist/SvSheet.svelte +1 -1
- package/dist/SvSheetChartSetup.svelte +1 -1
- package/dist/SvSheetConditionalFormat.svelte +1 -1
- package/dist/SvSheetDataValidation.svelte +1 -1
- package/dist/SvSheetEditRanges.svelte +1 -1
- package/dist/SvSheetErrors.svelte +1 -1
- package/dist/SvSheetEvaluate.svelte +1 -1
- package/dist/SvSheetFindReplace.svelte +1 -1
- package/dist/SvSheetFormatCells.svelte +1 -1
- package/dist/SvSheetGoalSeek.svelte +1 -1
- package/dist/SvSheetInsertFunction.svelte +1 -1
- package/dist/SvSheetIteration.svelte +1 -1
- package/dist/SvSheetLink.svelte +1 -1
- package/dist/SvSheetManageRules.svelte +1 -1
- package/dist/SvSheetNameManager.svelte +1 -1
- package/dist/SvSheetPageSetup.svelte +1 -1
- package/dist/SvSheetPasteSpecial.svelte +1 -1
- package/dist/SvSheetPivot.svelte +1 -1
- package/dist/SvSheetProtectSheet.svelte +1 -1
- package/dist/SvSheetRemoveDuplicates.svelte +1 -1
- package/dist/SvSheetRibbon.svelte +1 -1
- package/dist/SvSheetSizeDialog.svelte +1 -1
- package/dist/SvSheetSort.svelte +1 -1
- package/dist/SvSheetSparklines.svelte +1 -1
- package/dist/SvSheetTable.svelte +1 -1
- package/dist/SvSheetTabs.svelte +1 -1
- package/dist/SvSheetTextToColumns.svelte +1 -1
- package/dist/SvSheetValidationAlert.svelte +1 -1
- package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
- package/dist/designer/assets/{index-v61ZvIWw.js → index-CsdyIRos.js} +3 -3
- package/dist/designer/assets/{src-DkFgWld_.js → src-CSmsOfsG.js} +15 -15
- package/dist/designer/index.html +2 -2
- package/dist/fields/AiCell.svelte +41 -0
- package/dist/fields/AiCell.svelte.d.ts +5 -0
- package/dist/fields/AttachmentCell.svelte +1 -1
- package/dist/fields/AttachmentDialog.svelte +1 -1
- package/dist/fields/AttachmentEditor.svelte +1 -1
- package/dist/fields/AttachmentPreview.svelte +1 -1
- package/dist/fields/BaseAutomations.svelte +1 -1
- package/dist/fields/BaseChartView.svelte +1 -1
- package/dist/fields/BaseDashboardView.svelte +133 -0
- package/dist/fields/BaseDashboardView.svelte.d.ts +17 -0
- package/dist/fields/BaseImport.svelte +89 -0
- package/dist/fields/BaseImport.svelte.d.ts +15 -0
- package/dist/fields/BaseInboxView.svelte +112 -0
- package/dist/fields/BaseInboxView.svelte.d.ts +8 -0
- package/dist/fields/BaseListView.svelte +90 -0
- package/dist/fields/BaseListView.svelte.d.ts +8 -0
- package/dist/fields/BaseSearch.svelte +78 -0
- package/dist/fields/BaseSearch.svelte.d.ts +10 -0
- package/dist/fields/BaseTableView.svelte +28 -3
- package/dist/fields/BaseTableView.svelte.d.ts +5 -1
- package/dist/fields/BaseTabs.svelte +45 -8
- package/dist/fields/BaseTabs.svelte.d.ts +25 -1
- package/dist/fields/BaseTrash.svelte +63 -0
- package/dist/fields/BaseTrash.svelte.d.ts +15 -0
- package/dist/fields/CheckboxCell.svelte +1 -1
- package/dist/fields/ChecklistCell.svelte +22 -0
- package/dist/fields/ChecklistCell.svelte.d.ts +10 -0
- package/dist/fields/ChecklistEditor.svelte +81 -0
- package/dist/fields/ChecklistEditor.svelte.d.ts +12 -0
- package/dist/fields/ColorCell.svelte +13 -0
- package/dist/fields/ColorCell.svelte.d.ts +8 -0
- package/dist/fields/ColorEditor.svelte +60 -0
- package/dist/fields/ColorEditor.svelte.d.ts +11 -0
- package/dist/fields/DashboardRecords.svelte +35 -0
- package/dist/fields/DashboardRecords.svelte.d.ts +11 -0
- package/dist/fields/DashboardTileEditor.svelte +138 -0
- package/dist/fields/DashboardTileEditor.svelte.d.ts +15 -0
- package/dist/fields/DeleteFieldConfirm.svelte +1 -1
- package/dist/fields/DeleteRecordConfirm.svelte +1 -1
- package/dist/fields/FieldEditor.svelte +32 -3
- package/dist/fields/FieldInput.svelte +1 -1
- package/dist/fields/FieldsHeaderEnd.svelte +1 -1
- package/dist/fields/FootRowAdder.svelte +1 -1
- package/dist/fields/GroupHeader.svelte +3 -3
- package/dist/fields/LinkPickerEditor.svelte +1 -1
- package/dist/fields/LinkPreview.svelte +1 -1
- package/dist/fields/LinkedRecordView.svelte +1 -1
- package/dist/fields/LinkedRecordsCell.svelte +1 -1
- package/dist/fields/ListChips.svelte +21 -0
- package/dist/fields/ListChips.svelte.d.ts +9 -0
- package/dist/fields/LongTextEditor.svelte +1 -1
- package/dist/fields/MentionInput.svelte +59 -0
- package/dist/fields/MentionInput.svelte.d.ts +11 -0
- package/dist/fields/NumberEditor.svelte +1 -1
- package/dist/fields/OptionsEditor.svelte +1 -1
- package/dist/fields/PercentCell.svelte +1 -1
- package/dist/fields/PropertyInput.svelte +13 -10
- package/dist/fields/RatingCell.svelte +1 -1
- package/dist/fields/RatingEditor.svelte +1 -1
- package/dist/fields/RecordView.svelte +20 -25
- package/dist/fields/RowHeader.svelte +1 -1
- package/dist/fields/SelectCell.svelte +1 -1
- package/dist/fields/SelectEditor.svelte +1 -1
- package/dist/fields/SummaryCell.svelte +1 -1
- package/dist/fields/SvBase.svelte +48 -9
- package/dist/fields/SvBase.svelte.d.ts +33 -1
- package/dist/fields/SvBaseForm.svelte +2 -2
- package/dist/fields/SvBaseForm.svelte.d.ts +14 -0
- package/dist/fields/SvBaseViewBar.svelte +33 -12
- package/dist/fields/SvBaseViewBar.svelte.d.ts +2 -0
- package/dist/fields/TimeOfDayEditor.svelte +39 -0
- package/dist/fields/TimeOfDayEditor.svelte.d.ts +12 -0
- package/dist/fields/UserCell.svelte +1 -1
- package/dist/fields/activity.svelte.d.ts +29 -0
- package/dist/fields/activity.svelte.js +1 -1
- package/dist/fields/ai-field.svelte.d.ts +91 -0
- package/dist/fields/ai-field.svelte.js +1 -0
- package/dist/fields/ai-prompt.d.ts +64 -0
- package/dist/fields/ai-prompt.js +7 -0
- package/dist/fields/airtable.d.ts +90 -0
- package/dist/fields/airtable.js +1 -0
- package/dist/fields/bar-request.svelte.d.ts +1 -1
- package/dist/fields/base-history.d.ts +56 -0
- package/dist/fields/base-history.js +1 -0
- package/dist/fields/base-import.d.ts +54 -0
- package/dist/fields/base-import.js +2 -0
- package/dist/fields/base-search.d.ts +34 -0
- package/dist/fields/base-search.js +1 -0
- package/dist/fields/base-share.d.ts +45 -0
- package/dist/fields/base-share.js +1 -0
- package/dist/fields/base-sql.js +3 -3
- package/dist/fields/base-trash.d.ts +51 -0
- package/dist/fields/base-trash.js +1 -0
- package/dist/fields/builtin-types.js +1 -1
- package/dist/fields/chart-view.d.ts +12 -0
- package/dist/fields/chart-view.js +1 -1
- package/dist/fields/checklist.d.ts +36 -0
- package/dist/fields/checklist.js +4 -0
- package/dist/fields/color-value.d.ts +14 -0
- package/dist/fields/color-value.js +1 -0
- package/dist/fields/convert.js +1 -1
- package/dist/fields/copy-text.d.ts +1 -1
- package/dist/fields/copy-text.js +1 -1
- package/dist/fields/dashboard.d.ts +143 -0
- package/dist/fields/dashboard.js +1 -0
- package/dist/fields/field-access.svelte.d.ts +37 -0
- package/dist/fields/field-access.svelte.js +1 -0
- package/dist/fields/field-ops.js +1 -1
- package/dist/fields/filter-model.d.ts +4 -11
- package/dist/fields/filter-model.js +1 -1
- package/dist/fields/form-logic.d.ts +69 -0
- package/dist/fields/form-logic.js +1 -0
- package/dist/fields/formula.js +1 -1
- package/dist/fields/grid-access.d.ts +8 -0
- package/dist/fields/grid-access.js +1 -1
- package/dist/fields/index.d.ts +16 -0
- package/dist/fields/index.js +1 -1
- package/dist/fields/list-view.d.ts +40 -0
- package/dist/fields/list-view.js +1 -0
- package/dist/fields/mentions.d.ts +50 -0
- package/dist/fields/mentions.js +1 -0
- package/dist/fields/palette.d.ts +4 -2
- package/dist/fields/palette.js +1 -1
- package/dist/fields/record-menu.js +1 -1
- package/dist/fields/registry.svelte.d.ts +5 -0
- package/dist/fields/registry.svelte.js +1 -1
- package/dist/fields/time-of-day.d.ts +28 -0
- package/dist/fields/time-of-day.js +1 -0
- package/dist/fields/view-model.d.ts +24 -2
- package/dist/fields/view-model.js +1 -1
- package/dist/fields/viewbar/ChartPanel.svelte +1 -1
- package/dist/fields/viewbar/ColorPanel.svelte +1 -1
- package/dist/fields/viewbar/ConditionValue.svelte +4 -4
- package/dist/fields/viewbar/FilterPanel.svelte +1 -1
- package/dist/fields/viewbar/GanttPanel.svelte +1 -1
- package/dist/fields/viewbar/HideFieldsPanel.svelte +1 -1
- package/dist/fields/viewbar/ListPanel.svelte +36 -0
- package/dist/fields/viewbar/ListPanel.svelte.d.ts +11 -0
- package/dist/fields/viewbar/SortPanel.svelte +1 -1
- package/dist/fields/viewbar/ViewsMenu.svelte +27 -4
- package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +6 -0
- package/dist/gantt/SvGridGantt.svelte +1 -1
- package/dist/node/studio.js +1 -1
- package/dist/review/RichCellMark.svelte +1 -1
- package/dist/review/SvReviewPanel.svelte +1 -1
- package/dist/server/SvGroupCell.svelte +1 -1
- package/dist/server/SvRowGroupPanel.svelte +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/dist/wc/GridFind-DsTvdUXq.js +1 -0
- package/dist/wc/GridFooter-D-i8boBh.js +1 -0
- package/dist/wc/GridMenus-CYe9Fw2I.js +20 -0
- package/dist/wc/PinSplitter-LvyyrLhe.js +6 -0
- package/dist/wc/SvChartMenu-XKW_LOYw.js +1 -0
- package/dist/wc/SvDateRangeInput-CSOxqTB1.js +1 -0
- package/dist/wc/SvDateTimePicker-DvvFs2T9.js +4 -0
- package/dist/wc/SvField-BmQphyOs.js +20 -0
- package/dist/wc/SvForm-HD7y5vmk.js +46 -0
- package/dist/wc/SvGridCellEditor-776KAOe1.js +3 -0
- package/dist/wc/SvGridChart-DC7ZUhp8.js +171 -0
- package/dist/wc/SvGridChartBuilder-Dd3vWBvq.js +7 -0
- package/dist/wc/SvGridChartPanel-CwYjF46U.js +5 -0
- package/dist/wc/SvGridChartView-CSF38rBs.js +3 -0
- package/dist/wc/SvGridDropdown-4S1G7gsP.js +30 -0
- package/dist/wc/SvMenuList-D3ZLXjL_.js +1 -0
- package/dist/wc/SvModal-Dk0YwPWp.js +7 -0
- package/dist/wc/SvSwitchButton-DdZmc3ew.js +1 -0
- package/dist/wc/SvTabs-BI2cQHyw.js +2 -0
- package/dist/wc/base-react.d.ts +38 -0
- package/dist/wc/base-react.js +1 -0
- package/dist/wc/base-vue.d.ts +29 -0
- package/dist/wc/base-vue.js +1 -0
- package/dist/wc/board-RQp5fHPR.js +21 -0
- package/dist/wc/board-view.svelte-CpxuZcEg.js +1 -0
- package/dist/wc/card-marks.svelte-QwxIcKcZ.js +1 -0
- package/dist/wc/client-DNdLmGcu.js +3 -0
- package/dist/wc/createOverlay.svelte-CDw3RXgs.js +1 -0
- package/dist/wc/custom-filter-Dp8JxlQu.js +2 -0
- package/dist/wc/date-format-DtSmFyEB.js +18 -0
- package/dist/wc/editor-registry-CkKfcVLc.js +1 -0
- package/dist/wc/export-format-CGfE9_O5.js +5 -0
- package/dist/wc/gallery-CNOHNWEJ.js +4 -0
- package/dist/wc/gallery-view.svelte-27X-wCQH.js +1 -0
- package/dist/wc/grid-extension.svelte-hgqOteka.js +1 -0
- package/dist/wc/import-B9mIERCl.js +4 -0
- package/dist/wc/js-scroller.svelte-BP8Up6_q.js +1 -0
- package/dist/wc/license-CWVWqb-i.js +27 -0
- package/dist/wc/list-option-CI4nMshZ.js +1 -0
- package/dist/wc/react.d.ts +1 -0
- package/dist/wc/react.js +1 -1
- package/dist/wc/scheduler-CkVY4od-.js +147 -0
- package/dist/wc/scheduler-view.svelte-SzG7rU8b.js +1 -0
- package/dist/wc/sparkline-DWRBQubt.js +1 -0
- package/dist/wc/sv-base-element.d.ts +87 -0
- package/dist/wc/sv-base-element.js +273 -0
- package/dist/wc/sv-sheet-element.d.ts +2 -0
- package/dist/wc/sv-sheet-element.js +55 -55
- package/dist/wc/svelte-virtualizer.svelte-CSBwEZt9.js +1 -0
- package/dist/wc/types/sv-base-element.d.ts +87 -0
- package/dist/wc/vue.d.ts +1 -0
- package/dist/wc/vue.js +1 -1
- package/package.json +19 -4
|
@@ -2,6 +2,9 @@ import { type BaseRemoteChange } from './base-sync.js';
|
|
|
2
2
|
import { type BaseTable } from './base-tables.js';
|
|
3
3
|
import type { FieldView, FieldViewType } from './view-model.js';
|
|
4
4
|
import { type AutomationRun } from './automations.svelte.js';
|
|
5
|
+
import { type BaseTrashItem } from './base-trash.js';
|
|
6
|
+
import { type CanEditField } from './field-access.svelte.js';
|
|
7
|
+
import { type BaseShare } from './base-share.js';
|
|
5
8
|
type $$ComponentProps = {
|
|
6
9
|
/** Several tables, shown as tabs. Without it, `data` and `columns` are the one table. */
|
|
7
10
|
tables?: BaseTable[];
|
|
@@ -26,8 +29,37 @@ type $$ComponentProps = {
|
|
|
26
29
|
automations?: boolean;
|
|
27
30
|
/** Changes made in the database by someone else, once they are in the page (tables with a `source` that has `realtime`). */
|
|
28
31
|
onRemoteChange?: (changes: BaseRemoteChange[]) => void;
|
|
32
|
+
/** Undo and Redo buttons in the tab bar (default true). Ctrl+Z works either way. */
|
|
33
|
+
undoRedo?: boolean;
|
|
34
|
+
/** Deleted records, fields and tables, to restore (bind it, or keep it with `onTrashChange`, to store it). */
|
|
35
|
+
trash?: BaseTrashItem[];
|
|
36
|
+
onTrashChange?: (trash: BaseTrashItem[]) => void;
|
|
37
|
+
/** Days an item stays in the trash (0: until it is emptied). Default 30. */
|
|
38
|
+
trashDays?: number;
|
|
39
|
+
/** "Import a file" in the tab bar's menus (default true). */
|
|
40
|
+
fileImport?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Who may change a field's values, in place of each field's own
|
|
43
|
+
* `fieldProps.editors` list (roles, a server's answer). Applies to every
|
|
44
|
+
* base on the page, as `setCanEditField` does.
|
|
45
|
+
*/
|
|
46
|
+
canEditField?: CanEditField;
|
|
47
|
+
/** Whether the signed-in person may set who can edit a field, in the field editor (default true). */
|
|
48
|
+
protectFields?: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Look, do not touch (a share link): nothing can be edited, added or
|
|
51
|
+
* deleted, comments are read only, and view changes stay in the page.
|
|
52
|
+
* An object picks what is shown too: `{ tables, views, hideFields }`
|
|
53
|
+
* (ids; a hidden field takes the fields that read it along). Hiding is
|
|
54
|
+
* for display: send a copy without the data when it is secret.
|
|
55
|
+
*/
|
|
56
|
+
readOnly?: boolean | BaseShare;
|
|
57
|
+
/** The search box in the tab bar, over every table's records (default true; Ctrl+K focuses it). */
|
|
58
|
+
search?: boolean;
|
|
29
59
|
[prop: string]: any;
|
|
30
60
|
};
|
|
31
|
-
declare const SvBase: import("svelte").Component<$$ComponentProps, {
|
|
61
|
+
declare const SvBase: import("svelte").Component<$$ComponentProps, {
|
|
62
|
+
openImport: (mode?: "new" | "append", file?: File) => void;
|
|
63
|
+
}, "tables" | "trash" | "views" | "activeView" | "activeTable">;
|
|
32
64
|
type SvBase = ReturnType<typeof SvBase>;
|
|
33
65
|
export default SvBase;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{untrack}from"svelte";import{
|
|
2
|
+
import{untrack}from"svelte";import{fieldColumns,gridOf,primaryIdOf}from"./grid-access";import{newRowValues}from"./field-ops";import{linkHref}from"./links";import{compileFormConditions,formPrefillKey,formValue,prefillValue,readFormPrefill,settleFormAnswers}from"./form-logic";import FieldInput from"./FieldInput.svelte";import FieldIcon from"./viewbar/FieldIcon.svelte";let{api,fields,required=[],title="New record",description="",submitLabel="Submit",defaults,conditions,prefill,onSubmit}=$props();const COMPUTED=new Set(["formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button"]);const ctrl=$derived(api?gridOf(api):void 0);const columns=$derived.by(()=>{if(!ctrl)return[];const all=fieldColumns(ctrl).filter(c=>!COMPUTED.has(c.fieldType??"")&&c.def.editable!==false&&!c.def.fieldFn);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"Choose";if(t==="date")return"Pick a date";if(t==="attachment")return"Add files";if(t==="link")return"Link records";return"Type here"}let draft=$state({});let editing=$state(null);let errors=$state({});let sent=$state(false);let busy=$state(false);let failure=$state("");let seed=null;let prefilled={};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(next){const out=settleFormAnswers(next,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 next={};for(const c of columns){const v=start[c.field];if(v!==void 0&&!isBlank(v))next[c.field]=Array.isArray(v)?v.slice():v}const fromLink=readFormPrefill(prefill,columns);for(const c of columns){if(!(c.id in fromLink.values))continue;const v=prefillValue(c,fromLink.values[c.id],next);if(v!==void 0)next[c.field]=v}linkHidden=new Set(columns.filter(c=>fromLink.hide.has(c.id)&&!isBlank(next[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={...next};hidden=new Set;settle(next)}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:"Not a valid email address"},url:{kind:"url",message:"Not a valid web address"},phone:{kind:"phone",message:"Not a valid phone number"}};function problem(c,v){const blank=isBlank(v);if(blank&&required.includes(c.id))return`${c.header} is required`;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`${c.header} is not valid`;if(typeof verdict==="string"&&verdict)return verdict}return""}function editBeside(c,dir){const at=shown.findIndex(x=>x.id===c.id);const next=shown[at+dir];editing=next&&next.def.editorType!=="checkbox"?next.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}async function submit(e){e.preventDefault();if(!ctrl||busy)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]));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}function fail(row,err){const at=ctrl?ctrl.internalData.indexOf(row):-1;if(at>=0)api.removeRows([at]);failure=err instanceof Error&&err.message?err.message:"The record could not be sent. Try again."}function again(){seed=null;errors={};failure="";startRecord();sent=false}
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
{#if ctrl}
|
|
@@ -14,7 +14,7 @@ import{untrack}from"svelte";import{parseEditorValue}from"@svgrid/grid";import{fi
|
|
|
14
14
|
<form class="sv-fform" onsubmit={submit} novalidate>
|
|
15
15
|
<h2 class="sv-fform-title">{title}</h2>
|
|
16
16
|
{#if description}<p class="sv-fform-desc">{description}</p>{/if}
|
|
17
|
-
{#each
|
|
17
|
+
{#each shown as c (c.id)}
|
|
18
18
|
{@const v = draft[c.field]}
|
|
19
19
|
<div class="sv-fform-field" class:is-missing={!!errors[c.id]}>
|
|
20
20
|
<div class="sv-fform-label">
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { FieldFilter } from './filter-model.js';
|
|
2
|
+
import { type FormPrefill } from './form-logic.js';
|
|
1
3
|
type $$ComponentProps = {
|
|
2
4
|
/** The grid's api. */
|
|
3
5
|
api: any;
|
|
@@ -10,6 +12,18 @@ type $$ComponentProps = {
|
|
|
10
12
|
submitLabel?: string;
|
|
11
13
|
/** Values each record from this form starts with, under the row adder's `defaults` (`<SvBase>` gives an id). */
|
|
12
14
|
defaults?: () => Record<string, unknown>;
|
|
15
|
+
/**
|
|
16
|
+
* Column id -> when that field is shown, as a view bar filter over the
|
|
17
|
+
* other answers. A hidden field is not required, not checked, and not in
|
|
18
|
+
* the record; what was typed in it is cleared when it hides.
|
|
19
|
+
*/
|
|
20
|
+
conditions?: Record<string, FieldFilter>;
|
|
21
|
+
/**
|
|
22
|
+
* Answers to start with: a link or query string with
|
|
23
|
+
* `prefill_<Field name>=value` and `hide_<Field name>=true`, `true` for
|
|
24
|
+
* the page's own URL, or values by field name or column id.
|
|
25
|
+
*/
|
|
26
|
+
prefill?: FormPrefill;
|
|
13
27
|
/**
|
|
14
28
|
* After the row was added. Return a Promise to wait on it: the button is
|
|
15
29
|
* busy until it settles, and a rejection takes the row back out of the
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import{getRecordRequest}from"./editor-request.svelte";import{getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";let{api,views=$bindable([{id:"grid",name:"Grid view",type:"grid"}]),activeView=$bindable(""),onViewsChange,viewTypes,automations=null,changed=null,rowHeights=[{label:"Short",height:34},{label:"Medium",height:56},{label:"Tall",height:88},{label:"Extra tall",height:128}]}=$props();const ctrl=$derived(api?gridOf(api):void 0);const active=$derived(views.find(v=>v.id===activeView)??views[0]);const types=$derived(viewTypes??["grid","kanban","calendar",...hasGanttView()?["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;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")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});function switchTo(id){if(!ctrl||!active||id===active.id)return;const next=views.map(v=>v.id===active.id?capture(v):v);const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target);viewsOpen=false}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...views.map(v=>v.id===active.id?capture(v):v),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id?capture(active):views.find(v=>v.id===id);if(!src)return;const copy={...JSON.parse(JSON.stringify(src)),id:newViewId(),name:`${src.name} copy`};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)return;const next=views.filter(v=>v.id!==id);setViews(next);if(id===active?.id){activeView=next[0].id;void show(next[0])}}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));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));$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(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(()=>{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==="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"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)return`Filtered by ${columns.find(c=>ids.has(c.id))?.header??"1 field"}`;return`Filtered by ${ids.size} fields`});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(effectiveColor.mode==="field"?`Colored by ${columns.find(c=>c.field===effectiveColor.field)?.header??"field"}`:effectiveColor.mode==="conditions"&&effectiveColor.rules.length?"Colored by conditions":"Color");const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);$effect(()=>{const grouped=groupCount>0;void rowHeight;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});const records=$derived.by(()=>{if(!ctrl)return 0;const tops=(ctrl.allRows??[]).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)});const plural=(n,one,many)=>`${n} ${n===1?one:many}`;let searching=$state(false);const quickSearch=$derived(active?.type!=="grid");async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");root?.querySelector(".sv-grid-find-input")?.focus()}function focusBox(node){node.focus()}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]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const record=$derived.by(()=>{const r=getRecordRequest();const t=active?.type;return r&&ctrl&&r.ctrl===ctrl&&(t==="kanban"||t==="calendar"||t==="gantt"||t==="gallery")?r:null});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();const t=active?.type;return r&&ctrl&&r.ctrl===ctrl&&(t==="kanban"||t==="calendar"||t==="gantt"||t==="gallery")?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")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")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);return new Set(["hide","filter","sort"])});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"};
|
|
2
|
+
import{panelFocus}from"./viewbar/panel-focus";import{tick,untrack}from"svelte";import{SvPopover,hasGanttView}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";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 ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest}from"./editor-request.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";let{api,views=$bindable([{id:"grid",name:"Grid view",type:"grid"}]),activeView=$bindable(""),onViewsChange,viewTypes,automations=null,changed=null,lockViews=true,rowHeights=[{label:"Short",height:34},{label:"Medium",height:56},{label:"Tall",height:88},{label:"Extra tall",height:128}]}=$props();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`This view is locked${by?` by ${by}`:""}: its settings stay as saved`});const types=$derived(viewTypes??["grid","kanban","calendar",...hasGanttView()?["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;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")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;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){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);viewsOpen=false}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||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:`${src.name} copy`};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 next=views.filter(v=>v.id!==id);setViews(next);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));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));$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==="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"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)return`Filtered by ${columns.find(c=>ids.has(c.id))?.header??"1 field"}`;return`Filtered by ${ids.size} fields`});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(effectiveColor.mode==="field"?`Colored by ${columns.find(c=>c.field===effectiveColor.field)?.header??"field"}`:effectiveColor.mode==="conditions"&&effectiveColor.rules.length?"Colored by conditions":"Color");const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);$effect(()=>{const grouped=groupCount>0;void rowHeight;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});const records=$derived.by(()=>{if(!ctrl)return 0;const tops=(ctrl.allRows??[]).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)});const plural=(n,one,many)=>`${n} ${n===1?one:many}`;let searching=$state(false);const quickSearch=$derived(active?.type!=="grid");async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");root?.querySelector(".sv-grid-find-input")?.focus()}function focusBox(node){node.focus()}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]);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==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r: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;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")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 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)}
|
|
@@ -18,22 +18,33 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
18
18
|
{/snippet}
|
|
19
19
|
<ViewsMenu
|
|
20
20
|
{ctrl}
|
|
21
|
-
{
|
|
21
|
+
views={visible}
|
|
22
22
|
activeId={active.id}
|
|
23
23
|
{types}
|
|
24
|
+
{me}
|
|
25
|
+
canLock={lockViews}
|
|
24
26
|
onSwitch={switchTo}
|
|
25
27
|
onCreate={create}
|
|
26
28
|
onRename={rename}
|
|
27
29
|
onDuplicate={duplicate}
|
|
28
30
|
onDelete={remove}
|
|
31
|
+
onLock={toggleLock}
|
|
29
32
|
/>
|
|
30
33
|
</SvPopover>
|
|
34
|
+
{#if locked}
|
|
35
|
+
<span class="sv-fvb-lock" title={lockTitle}>
|
|
36
|
+
{@render glyph(ICON.lock, 13)}<span>{lockedDirty ? 'Locked, not saved' : 'Locked'}</span>
|
|
37
|
+
{#if lockedDirty}<button type="button" class="sv-fvb-lock-reset" onclick={resetLocked}>Reset</button>{/if}
|
|
38
|
+
</span>
|
|
39
|
+
{:else if active.personal}
|
|
40
|
+
<span class="sv-fvb-lock" title="A personal view: only you see it">{@render glyph(ICON.person, 13)}<span>Personal</span></span>
|
|
41
|
+
{/if}
|
|
31
42
|
<span class="sv-fvb-sep" aria-hidden="true"></span>
|
|
32
43
|
|
|
33
44
|
{#if has.has('hide')}
|
|
34
45
|
<SvPopover open={panel === 'hide'} onOpenChange={(o) => setPanel('hide', o)} arrow={false} placement="bottom-start" ariaLabel="Hide fields">
|
|
35
46
|
{#snippet anchor()}
|
|
36
|
-
<button type="button" class="sv-fvb-btn" class:is-set={hiddenCount > 0}>
|
|
47
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={hiddenCount > 0}>
|
|
37
48
|
{@render glyph(ICON.hide)}<span>{hiddenCount ? plural(hiddenCount, 'hidden field', 'hidden fields') : 'Hide fields'}</span>
|
|
38
49
|
</button>
|
|
39
50
|
{/snippet}
|
|
@@ -43,7 +54,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
43
54
|
{#if has.has('filter')}
|
|
44
55
|
<SvPopover open={panel === 'filter'} onOpenChange={(o) => setPanel('filter', o)} arrow={false} placement="bottom-start" ariaLabel="Filter">
|
|
45
56
|
{#snippet anchor()}
|
|
46
|
-
<button type="button" class="sv-fvb-btn" class:is-set={filterCount > 0}>{@render glyph(ICON.filter)}<span>{filterLabel}</span></button>
|
|
57
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={filterCount > 0}>{@render glyph(ICON.filter)}<span>{filterLabel}</span></button>
|
|
47
58
|
{/snippet}
|
|
48
59
|
<FilterPanel {ctrl} {api} />
|
|
49
60
|
</SvPopover>
|
|
@@ -51,7 +62,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
51
62
|
{#if has.has('group')}
|
|
52
63
|
<SvPopover open={panel === 'group'} onOpenChange={(o) => setPanel('group', o)} arrow={false} placement="bottom-start" ariaLabel="Group">
|
|
53
64
|
{#snippet anchor()}
|
|
54
|
-
<button type="button" class="sv-fvb-btn" class:is-set={groupCount > 0}>
|
|
65
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={groupCount > 0}>
|
|
55
66
|
{@render glyph(ICON.group)}<span>{groupCount ? `Grouped by ${plural(groupCount, 'field', 'fields')}` : 'Group'}</span>
|
|
56
67
|
</button>
|
|
57
68
|
{/snippet}
|
|
@@ -61,7 +72,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
61
72
|
{#if has.has('sort')}
|
|
62
73
|
<SvPopover open={panel === 'sort'} onOpenChange={(o) => setPanel('sort', o)} arrow={false} placement="bottom-start" ariaLabel="Sort">
|
|
63
74
|
{#snippet anchor()}
|
|
64
|
-
<button type="button" class="sv-fvb-btn" class:is-set={sortCount > 0}>
|
|
75
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={sortCount > 0}>
|
|
65
76
|
{@render glyph(ICON.sort)}<span>{sortCount ? `Sorted by ${plural(sortCount, 'field', 'fields')}` : 'Sort'}</span>
|
|
66
77
|
</button>
|
|
67
78
|
{/snippet}
|
|
@@ -71,7 +82,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
71
82
|
{#if has.has('color')}
|
|
72
83
|
<SvPopover open={panel === 'color'} onOpenChange={(o) => setPanel('color', o)} arrow={false} placement="bottom-start" ariaLabel="Color">
|
|
73
84
|
{#snippet anchor()}
|
|
74
|
-
<button type="button" class="sv-fvb-btn" class:is-set={effectiveColor.mode !== 'none'}>{@render glyph(ICON.color)}<span>{colorLabel}</span></button>
|
|
85
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={effectiveColor.mode !== 'none'}>{@render glyph(ICON.color)}<span>{colorLabel}</span></button>
|
|
75
86
|
{/snippet}
|
|
76
87
|
<ColorPanel {ctrl} setting={effectiveColor} onChange={setColor} />
|
|
77
88
|
</SvPopover>
|
|
@@ -80,7 +91,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
80
91
|
{@const chart = active.chart ?? NO_CHART}
|
|
81
92
|
<SvPopover open={panel === 'chart'} onOpenChange={(o) => setPanel('chart', o)} arrow={false} placement="bottom-start" ariaLabel="Customize chart">
|
|
82
93
|
{#snippet anchor()}
|
|
83
|
-
<button type="button" class="sv-fvb-btn">{@render glyph(ICON.chart)}<span>Customize chart</span></button>
|
|
94
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn">{@render glyph(ICON.chart)}<span>Customize chart</span></button>
|
|
84
95
|
{/snippet}
|
|
85
96
|
<ChartPanel {ctrl} setting={chart} onChange={setChart} />
|
|
86
97
|
</SvPopover>
|
|
@@ -89,15 +100,25 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
89
100
|
{@const settings = active}
|
|
90
101
|
<SvPopover open={panel === 'gantt'} onOpenChange={(o) => setPanel('gantt', o)} arrow={false} placement="bottom-start" ariaLabel="Customize timeline">
|
|
91
102
|
{#snippet anchor()}
|
|
92
|
-
<button type="button" class="sv-fvb-btn">{@render glyph(ICON.gantt)}<span>Customize timeline</span></button>
|
|
103
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn">{@render glyph(ICON.gantt)}<span>Customize timeline</span></button>
|
|
93
104
|
{/snippet}
|
|
94
105
|
<GanttPanel {ctrl} view={settings} onChange={setGantt} />
|
|
95
106
|
</SvPopover>
|
|
96
107
|
{/if}
|
|
108
|
+
{#if has.has('list') && active}
|
|
109
|
+
{@const settings = active}
|
|
110
|
+
{@const what = active.type === 'inbox' ? 'inbox' : 'list'}
|
|
111
|
+
<SvPopover open={panel === 'list'} onOpenChange={(o) => setPanel('list', o)} arrow={false} placement="bottom-start" ariaLabel={`Customize ${what}`}>
|
|
112
|
+
{#snippet anchor()}
|
|
113
|
+
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn">{@render glyph(viewTypeInfo(settings.type).icon)}<span>Customize {what}</span></button>
|
|
114
|
+
{/snippet}
|
|
115
|
+
<ListPanel {ctrl} view={settings} inbox={settings.type === 'inbox'} onChange={setList} />
|
|
116
|
+
</SvPopover>
|
|
117
|
+
{/if}
|
|
97
118
|
{#if has.has('height')}
|
|
98
119
|
<SvPopover arrow={false} placement="bottom-start" ariaLabel="Row height">
|
|
99
120
|
{#snippet anchor()}
|
|
100
|
-
<button type="button" class="sv-fvb-btn sv-fvb-icon-only" aria-label="Row height" title="Row height">{@render glyph(ICON.height)}</button>
|
|
121
|
+
<button type="button" disabled={locked} class="sv-fvb-btn sv-fvb-icon-only" aria-label="Row height" title={locked ? lockTitle : "Row height"}>{@render glyph(ICON.height)}</button>
|
|
101
122
|
{/snippet}
|
|
102
123
|
<div class="sv-fvb-panel sv-fvb-heights" role="menu" aria-label="Row height" use:panelFocus>
|
|
103
124
|
{#each rowHeights as h (h.height)}
|
|
@@ -128,7 +149,7 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
128
149
|
{@render glyph(ICON.bolt)}<span>{automations.count ? plural(automations.count, 'automation', 'automations') : 'Automations'}</span>
|
|
129
150
|
</button>
|
|
130
151
|
{/if}
|
|
131
|
-
{#if active.type !== 'form'}
|
|
152
|
+
{#if active.type !== 'form' && active.type !== 'dashboard'}
|
|
132
153
|
<span class="sv-fvb-count" aria-live="polite">{plural(records, 'record', 'records')}</span>
|
|
133
154
|
{#if quickSearch && (searching || ctrl.globalFilter)}
|
|
134
155
|
<label class="sv-fvb-search">
|
|
@@ -168,5 +189,5 @@ import{tick,untrack}from"svelte";import{hasGanttView}from"@svgrid/grid";import{c
|
|
|
168
189
|
{/if}
|
|
169
190
|
|
|
170
191
|
<style>
|
|
171
|
-
.sv-fvb-changed{color:var(--sg-fg, #0f172a)}.sv-fvb-changed-dot{width:7px;height:7px;border-radius:50%;background:var(--sg-accent, #2563eb);flex:none}.sv-fvb{container-type:inline-size;display:flex;align-items:center;gap:2px;flex-wrap:wrap;min-height:40px;padding:4px 6px;font-family:var(--sg-font, inherit);font-size:13px;color:var(--sg-fg, #0f172a);border-bottom:1px solid var(--sg-border, #e2e8f0);background:var(--sg-bg, #fff)}.sv-fvb-btn{position:relative;display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;cursor:pointer;white-space:nowrap}.sv-fvb-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:-2px}.sv-fvb-btn.is-set{background:color-mix(in srgb,var(--sg-accent, #2563eb) 13%,transparent)}.sv-fvb-view{font-weight:600;max-width:240px}.sv-fvb-view-name{overflow:hidden;text-overflow:ellipsis}.sv-fvb-icon-only{padding:0 6px}.sv-fvb-sep{width:1px;height:18px;margin:0 6px;background:var(--sg-border, #e2e8f0)}.sv-fvb-spacer{flex:1}@container (max-width: 640px){.sv-fvb-btn:not(.sv-fvb-view)>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-btn{padding:0 6px}.sv-fvb-view{max-width:150px}}@container (max-width: 420px){.sv-fvb-count{display:none}}.sv-fvb-search{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-fvb-search input{width:160px;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit}.sv-fvb-search:focus-within{border-color:var(--sg-accent, #2563eb)}.sv-fvb-count{color:var(--sg-muted, #64748b);font-size:12px;margin-inline-end:4px;font-variant-numeric:tabular-nums}:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){max-width:min(94vw,760px)}:global(.sv-fvb-panel){font-size:13px;max-width:100%}:global(.sv-fvb-title){margin:0 0 6px;color:var(--sg-muted, #64748b);font-size:12px}:global(.sv-fvb-empty){margin:2px 0 8px;color:var(--sg-muted, #64748b)}:global(.sv-fvb-foot){display:flex;gap:12px;margin-top:8px;align-items:center}:global(.sv-fvb-select),:global(.sv-fvb-input){width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;font:inherit;font-size:13px;color:inherit;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #cbd5e1);border-radius:6px}:global(.sv-fvb-select:focus-visible),:global(.sv-fvb-input:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:-1px}:global(.sv-fvb-text-btn){border:0;padding:2px 0;background:none;font:inherit;color:var(--sg-accent, #2563eb);cursor:pointer}:global(.sv-fvb-text-btn:hover){text-decoration:underline}:global(.sv-fvb-solid-btn){border:0;border-radius:6px;padding:5px 12px;font:inherit;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-accent-fg, #fff)}:global(.sv-fvb-icon-btn){display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:6px;background:none;color:var(--sg-muted, #64748b);cursor:pointer}:global(.sv-fvb-icon-btn:hover){background:var(--sg-row-hover-bg, #f1f5f9);color:var(--sg-fg, #0f172a)}:global(.sv-fvb-switch){appearance:none;flex:none;position:relative;width:26px;height:15px;margin:0;border-radius:999px;cursor:pointer;background:color-mix(in srgb,var(--sg-fg, #0f172a) 22%,transparent);transition:background-color .12s}:global(.sv-fvb-switch:before){content:"";position:absolute;top:2px;left:2px;width:11px;height:11px;border-radius:50%;background:var(--sg-bg, #fff);transition:transform .12s}:global(.sv-fvb-switch:checked){background:var(--sg-accent, #2563eb)}:global(.sv-fvb-switch:checked:before){transform:translate(11px)}:global(.sv-fvb-switch:disabled){opacity:.5;cursor:default}:global(.sv-fvb-switch:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-fvb-heights{display:grid;min-width:150px}.sv-fvb-height{display:flex;align-items:center;gap:10px;padding:6px 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer}.sv-fvb-height:hover,.sv-fvb-height.is-on{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-height.is-on{font-weight:600}.sv-fvb-height-mark{width:14px;height:14px;border:1.5px solid currentColor;border-radius:3px;box-sizing:border-box;background:repeating-linear-gradient(to bottom,transparent 0 2px,currentColor 2px 3px) center / 8px calc(var(--lines) * 3px) no-repeat}
|
|
192
|
+
.sv-fvb-changed{color:var(--sg-fg, #0f172a)}.sv-fvb-changed-dot{width:7px;height:7px;border-radius:50%;background:var(--sg-accent, #2563eb);flex:none}.sv-fvb{container-type:inline-size;display:flex;align-items:center;gap:2px;flex-wrap:wrap;min-height:40px;padding:4px 6px;font-family:var(--sg-font, inherit);font-size:13px;color:var(--sg-fg, #0f172a);border-bottom:1px solid var(--sg-border, #e2e8f0);background:var(--sg-bg, #fff)}.sv-fvb-btn{position:relative;display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;cursor:pointer;white-space:nowrap}.sv-fvb-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:-2px}.sv-fvb-btn.is-set{background:color-mix(in srgb,var(--sg-accent, #2563eb) 13%,transparent)}.sv-fvb-view{font-weight:600;max-width:240px}.sv-fvb-view-name{overflow:hidden;text-overflow:ellipsis}.sv-fvb-icon-only{padding:0 6px}.sv-fvb-sep{width:1px;height:18px;margin:0 6px;background:var(--sg-border, #e2e8f0)}.sv-fvb-lock{display:inline-flex;flex:none;align-items:center;gap:4px;height:24px;margin-left:4px;padding:0 8px;border-radius:999px;font-size:12px;color:var(--sg-muted, #64748b);background:color-mix(in srgb,var(--sg-fg, #0f172a) 7%,transparent)}.sv-fvb-lock-reset{margin-left:2px;padding:0;border:0;background:none;font:inherit;font-weight:600;color:var(--sg-accent, #2563eb);cursor:pointer}:global(.sv-fvb-btn:disabled){opacity:.45;cursor:default}.sv-fvb-spacer{flex:1}@container (max-width: 640px){.sv-fvb-btn:not(.sv-fvb-view)>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-btn{padding:0 6px}.sv-fvb-view{max-width:150px}.sv-fvb-lock>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-lock{padding:0 6px}}@container (max-width: 420px){.sv-fvb-count{display:none}}.sv-fvb-search{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-fvb-search input{width:160px;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit}.sv-fvb-search:focus-within{border-color:var(--sg-accent, #2563eb)}.sv-fvb-count{color:var(--sg-muted, #64748b);font-size:12px;margin-inline-end:4px;font-variant-numeric:tabular-nums}:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){max-width:min(94vw,760px)}:global(.sv-fvb-panel){font-size:13px;max-width:100%}:global(.sv-fvb-title){margin:0 0 6px;color:var(--sg-muted, #64748b);font-size:12px}:global(.sv-fvb-empty){margin:2px 0 8px;color:var(--sg-muted, #64748b)}:global(.sv-fvb-foot){display:flex;gap:12px;margin-top:8px;align-items:center}:global(.sv-fvb-select),:global(.sv-fvb-input){width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;font:inherit;font-size:13px;color:inherit;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #cbd5e1);border-radius:6px}:global(.sv-fvb-select:focus-visible),:global(.sv-fvb-input:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:-1px}:global(.sv-fvb-text-btn){border:0;padding:2px 0;background:none;font:inherit;color:var(--sg-accent, #2563eb);cursor:pointer}:global(.sv-fvb-text-btn:hover){text-decoration:underline}:global(.sv-fvb-solid-btn){border:0;border-radius:6px;padding:5px 12px;font:inherit;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-accent-fg, #fff)}:global(.sv-fvb-icon-btn){display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:6px;background:none;color:var(--sg-muted, #64748b);cursor:pointer}:global(.sv-fvb-icon-btn:hover){background:var(--sg-row-hover-bg, #f1f5f9);color:var(--sg-fg, #0f172a)}:global(.sv-fvb-switch){appearance:none;flex:none;position:relative;width:26px;height:15px;margin:0;border-radius:999px;cursor:pointer;background:color-mix(in srgb,var(--sg-fg, #0f172a) 22%,transparent);transition:background-color .12s}:global(.sv-fvb-switch:before){content:"";position:absolute;top:2px;left:2px;width:11px;height:11px;border-radius:50%;background:var(--sg-bg, #fff);transition:transform .12s}:global(.sv-fvb-switch:checked){background:var(--sg-accent, #2563eb)}:global(.sv-fvb-switch:checked:before){transform:translate(11px)}:global(.sv-fvb-switch:disabled){opacity:.5;cursor:default}:global(.sv-fvb-switch:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}.sv-fvb-heights{display:grid;min-width:150px}.sv-fvb-height{display:flex;align-items:center;gap:10px;padding:6px 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer}.sv-fvb-height:hover,.sv-fvb-height.is-on{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-height.is-on{font-weight:600}.sv-fvb-height-mark{width:14px;height:14px;border:1.5px solid currentColor;border-radius:3px;box-sizing:border-box;background:repeating-linear-gradient(to bottom,transparent 0 2px,currentColor 2px 3px) center / 8px calc(var(--lines) * 3px) no-repeat}
|
|
172
193
|
</style>
|
|
@@ -25,6 +25,8 @@ type Props = {
|
|
|
25
25
|
label: string;
|
|
26
26
|
onSeen: () => void;
|
|
27
27
|
} | null;
|
|
28
|
+
/** Whether the person may lock and unlock views (default true). */
|
|
29
|
+
lockViews?: boolean;
|
|
28
30
|
};
|
|
29
31
|
declare const SvBaseViewBar: import("svelte").Component<Props, {}, "views" | "activeView">;
|
|
30
32
|
type SvBaseViewBar = ReturnType<typeof SvBaseViewBar>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import{portalToBody}from"@svgrid/grid";import{onMount}from"svelte";import{fieldPropsOf}from"./registry.svelte";import{formatTimeOfDay,parseTimeOfDay,timeFromSeconds,timeSeconds}from"./time-of-day";let{value,typed=false,columnDef,onCommit,onCancel,onCommitAndMove,onCommitAndMoveDown}=$props();const p=$derived(fieldPropsOf(columnDef??{}));const seeded=typed;let text=$state(typed?String(value??""):value==null||value===""?"":formatTimeOfDay(value,fieldPropsOf(columnDef??{})));const result=$derived(text.trim()?parseTimeOfDay(text,{seconds:!!p.showSeconds}):null);const error=$derived(text.trim()&&result==null?"Not a time (9:30 am, 14:05, 2pm)":null);const reads=$derived(result?formatTimeOfDay(result,p):"");function bump(dir,big){const now=text.trim()?timeSeconds(result):9*3600-dir*900;if(now==null)return;text=formatTimeOfDay(timeFromSeconds(now+dir*(big?3600:900)),p)}let box=$state(null);let input=$state(null);let noteAt=$state(null);function place(){const cell=box?.closest("td")??box;if(!cell)return;const r=cell.getBoundingClientRect();noteAt={top:r.bottom+2,left:r.left}}function takeFocus(){if(!input||document.activeElement===input)return;input.focus({preventScroll:true});if(!seeded)input.select();else input.setSelectionRange(text.length,text.length)}onMount(()=>{place();takeFocus();const frame=requestAnimationFrame(takeFocus);const onDown=e=>{if(finished||box?.contains(e.target))return;if(error){finished=true;onCancel()}else finish("commit")};window.addEventListener("resize",place);window.addEventListener("scroll",place,true);document.addEventListener("pointerdown",onDown,true);return()=>{cancelAnimationFrame(frame);window.removeEventListener("resize",place);window.removeEventListener("scroll",place,true);document.removeEventListener("pointerdown",onDown,true)}});let finished=false;function finish(how){if(finished||error)return;finished=true;if((how==="down"||how==="up")&&onCommitAndMoveDown)onCommitAndMoveDown(result,how==="up");else if((how==="next"||how==="prev")&&onCommitAndMove)onCommitAndMove(result,how==="next"?1:-1);else onCommit(result)}function onKey(e){if(e.key==="Enter")finish(e.shiftKey?"up":"down");else if(e.key==="Tab")finish(e.shiftKey?"prev":"next");else if(e.key==="ArrowUp"||e.key==="ArrowDown")bump(e.key==="ArrowUp"?1:-1,e.shiftKey);else if(e.key==="Escape"){finished=true;onCancel()}else{e.stopPropagation();return}e.preventDefault();e.stopPropagation()}const inputValue=e=>e.currentTarget.value;
|
|
3
|
+
</script>
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
<span
|
|
9
|
+
class="sv-fte"
|
|
10
|
+
class:is-invalid={!!error}
|
|
11
|
+
bind:this={box}
|
|
12
|
+
onpointerdown={(e) => e.stopPropagation()}
|
|
13
|
+
onmousedown={(e) => e.stopPropagation()}
|
|
14
|
+
onclick={(e) => e.stopPropagation()}
|
|
15
|
+
ondblclick={(e) => e.stopPropagation()}
|
|
16
|
+
>
|
|
17
|
+
<input
|
|
18
|
+
bind:this={input}
|
|
19
|
+
class="sv-fte-input"
|
|
20
|
+
autocomplete="off"
|
|
21
|
+
spellcheck="false"
|
|
22
|
+
placeholder={p.timeFormat === '24hour' ? '14:05' : '2:05 PM'}
|
|
23
|
+
aria-label="Time of day"
|
|
24
|
+
aria-invalid={error ? 'true' : undefined}
|
|
25
|
+
value={text}
|
|
26
|
+
oninput={(e) => (text = inputValue(e))}
|
|
27
|
+
onkeydown={onKey}
|
|
28
|
+
/>
|
|
29
|
+
</span>
|
|
30
|
+
|
|
31
|
+
{#if noteAt && (error || (reads && reads !== text.trim()))}
|
|
32
|
+
<div class="sv-fte-note" class:is-error={!!error} role={error ? 'alert' : 'status'} use:portalToBody style:top={`${noteAt.top}px`} style:left={`${noteAt.left}px`}>
|
|
33
|
+
{error ?? reads}
|
|
34
|
+
</div>
|
|
35
|
+
{/if}
|
|
36
|
+
|
|
37
|
+
<style>
|
|
38
|
+
.sv-fte{position:absolute;inset:0;z-index:1;display:flex;align-items:center;padding:0 var(--sg-cell-px, 7px);box-sizing:border-box;background:var(--sg-input-bg, var(--sg-bg, #fff))}.sv-fte:focus-within{box-shadow:inset 0 0 0 2px var(--sg-accent, #2563eb)}.sv-fte.is-invalid{box-shadow:inset 0 0 0 2px var(--sg-danger, #dc2626)}.sv-fte-input{width:100%;min-width:0;height:100%;padding:0;margin:0;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit;font-variant-numeric:tabular-nums}.sv-fte-note{position:fixed;z-index:2147483646;padding:3px 8px;border-radius:var(--sg-radius, 6px);pointer-events:none;background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);font-size:12px;white-space:nowrap}.sv-fte-note.is-error{background:var(--sg-danger, #dc2626);color:#fff}
|
|
39
|
+
</style>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type $$ComponentProps = {
|
|
2
|
+
value: unknown;
|
|
3
|
+
typed?: boolean;
|
|
4
|
+
columnDef?: Record<string, unknown>;
|
|
5
|
+
onCommit: (v?: unknown) => void;
|
|
6
|
+
onCancel: () => void;
|
|
7
|
+
onCommitAndMove?: (v: unknown, direction: 1 | -1) => void;
|
|
8
|
+
onCommitAndMoveDown?: (v: unknown, up?: boolean) => void;
|
|
9
|
+
};
|
|
10
|
+
declare const TimeOfDayEditor: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
11
|
+
type TimeOfDayEditor = ReturnType<typeof TimeOfDayEditor>;
|
|
12
|
+
export default TimeOfDayEditor;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{findFieldUser}from"./sources.svelte";let{value}=$props();const list=$derived((Array.isArray(value)?value:value==null||value===""?[]:[value]).map(v=>v&&typeof v==="object"?v:findFieldUser(v)??{id:String(v),name:String(v)}).filter(u=>!!u));const label=$derived(list.map(u=>u.name).join(", "));
|
|
2
|
+
import{findFieldUser}from"./sources.svelte";import UserFace from"./UserFace.svelte";let{value}=$props();const list=$derived((Array.isArray(value)?value:value==null||value===""?[]:[value]).map(v=>v&&typeof v==="object"?v:findFieldUser(v)??{id:String(v),name:String(v)}).filter(u=>!!u));const label=$derived(list.map(u=>u.name).join(", "));
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
<span class="sv-fus" title={label} aria-label={label || 'Nobody'}>
|
|
@@ -1,11 +1,19 @@
|
|
|
1
|
+
import { type FieldUser } from './sources.svelte.js';
|
|
1
2
|
export type RecordComment = {
|
|
2
3
|
id: string;
|
|
3
4
|
rowId: string;
|
|
4
5
|
/** The table of `<SvBase tables>` the record is in. */
|
|
5
6
|
tableId?: string;
|
|
7
|
+
/**
|
|
8
|
+
* What was written. A mention is kept inline as `@[Name](userId)` (see
|
|
9
|
+
* `mentionToken`): the record view draws it as the person's current name,
|
|
10
|
+
* so a rename does not break it. `mentionText` gives the text with `@Name`.
|
|
11
|
+
*/
|
|
6
12
|
text: string;
|
|
7
13
|
at: number;
|
|
8
14
|
by?: string;
|
|
15
|
+
/** The ids of the people the text mentions, in order; absent when it mentions nobody. */
|
|
16
|
+
mentions?: string[];
|
|
9
17
|
};
|
|
10
18
|
/** Which record a comment store is asked about, beyond its row id. */
|
|
11
19
|
export type RecordCommentContext = {
|
|
@@ -14,10 +22,26 @@ export type RecordCommentContext = {
|
|
|
14
22
|
/** The grid's api. */
|
|
15
23
|
api: unknown;
|
|
16
24
|
};
|
|
25
|
+
/** What a mention hook hears: a comment that mentions people, once per comment. */
|
|
26
|
+
export type MentionEvent = {
|
|
27
|
+
comment: RecordComment;
|
|
28
|
+
/** The people it mentions; one not in `setFieldUsers` comes with the name written in the comment. */
|
|
29
|
+
mentioned: FieldUser[];
|
|
30
|
+
rowId: string;
|
|
31
|
+
/** The table of `<SvBase tables>` the record is in; undefined for a single table or a plain grid. */
|
|
32
|
+
tableId?: string;
|
|
33
|
+
/** The record's row object, when the grid still has it. */
|
|
34
|
+
record: Record<string, unknown> | undefined;
|
|
35
|
+
/** The grid's api. */
|
|
36
|
+
api: unknown;
|
|
37
|
+
};
|
|
38
|
+
export type MentionHandler = (event: MentionEvent) => void;
|
|
17
39
|
/** Where comments are kept: the app's backend, or memory by default. */
|
|
18
40
|
export type RecordCommentStore = {
|
|
19
41
|
list: (rowId: string, api: unknown, context: RecordCommentContext) => ReadonlyArray<RecordComment>;
|
|
20
42
|
add: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void;
|
|
43
|
+
/** A comment that mentions people was added (after `add`): send the notifications here. */
|
|
44
|
+
onMention?: MentionHandler;
|
|
21
45
|
};
|
|
22
46
|
export type RecordChange = {
|
|
23
47
|
at: number;
|
|
@@ -59,6 +83,11 @@ export type ActivityScope = object | string | {
|
|
|
59
83
|
export declare function tableIdOf(ctrl: any): string | undefined;
|
|
60
84
|
/** Keep comments in the app's store (null: back to memory). */
|
|
61
85
|
export declare function setRecordComments(next: RecordCommentStore | null): void;
|
|
86
|
+
/**
|
|
87
|
+
* Hear every comment that mentions people, whichever store keeps it (memory
|
|
88
|
+
* too); null stops. A store's own `onMention` is called as well, first.
|
|
89
|
+
*/
|
|
90
|
+
export declare function setMentionHandler(next: MentionHandler | null): void;
|
|
62
91
|
/**
|
|
63
92
|
* Note a change to a cell (called after every edit, paste, fill and clear).
|
|
64
93
|
* `scope` is the grid, or the table (its base and id) for a change made
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCurrentUser}from"./sources.svelte.js";let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;version+=1}export function noteChange(scope,rowId,columnId,value,automation,via){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push({at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);version+=1}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,ctrl,false)?.get(rowId)??[]}let seq=0;export function addComment(ctrl,rowId,text){const body=text.trim();if(!body)return;const context=contextOf(ctrl);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id};if(
|
|
1
|
+
import{untrack}from"svelte";import{findFieldUser,getCurrentUser}from"./sources.svelte.js";import{mentionIds,parseMentions}from"./mentions.js";let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;let mentionHandler=null;export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;untrack(()=>version+=1)}export function setMentionHandler(next){mentionHandler=next}export function noteChange(scope,rowId,columnId,value,automation,via){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push({at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);version+=1}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});const commentScope=ctrl=>{const tableId=tableIdOf(ctrl);return tableId?{tableId}:ctrl};export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,commentScope(ctrl),false)?.get(rowId)??[]}let seq=0;export function addComment(ctrl,rowId,text){const body=text.trim();if(!body)return;const context=contextOf(ctrl);const mentions=mentionIds(body);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id,...mentions.length?{mentions}:{}};const kept=store;if(kept)kept.add(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,[...byRow.get(rowId)??[],comment])}version+=1;if(!mentions.length||!kept?.onMention&&!mentionHandler)return;const written=new Map(parseMentions(body).flatMap(p=>"mention"in p?[[p.mention,p.name]]:[]));const event={comment,mentioned:mentions.map(id=>findFieldUser(id)??{id,name:written.get(id)||id}),rowId,...context.tableId?{tableId:context.tableId}:{},record:(ctrl?.allRows??[]).find(r=>r.id===rowId)?.original,api:context.api};for(const hook of[kept?.onMention,mentionHandler]){try{hook?.(event)}catch(err){console.error(err)}}}export function timeAgo(at,now=Date.now()){const s=Math.max(0,Math.round((now-at)/1e3));if(s<45)return"just now";const m=Math.round(s/60);if(m<60)return`${m} minute${m===1?"":"s"} ago`;const h=Math.round(m/60);if(h<24)return`${h} hour${h===1?"":"s"} ago`;return new Date(at).toLocaleDateString()}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { type FieldTypeDef } from './registry.svelte.js';
|
|
2
|
+
export type { AIFieldProps, AIFieldOutput } from './ai-prompt.js';
|
|
3
|
+
/** A cell's generation, while it waits or runs, or after it failed. Nothing once its value is written. */
|
|
4
|
+
export type AIFieldCellState = {
|
|
5
|
+
status: 'queued' | 'running' | 'error';
|
|
6
|
+
message?: string;
|
|
7
|
+
};
|
|
8
|
+
/** What `generateAIField` did: values written, and cells that failed or were cancelled. */
|
|
9
|
+
export type AIFieldRun = {
|
|
10
|
+
written: number;
|
|
11
|
+
failed: number;
|
|
12
|
+
};
|
|
13
|
+
export declare const NO_PROVIDER = "No AI provider. The app sets one with setAIProvider() from @svgrid/grid.";
|
|
14
|
+
export declare const AI_ICON = "M10 3l1.8 5.2L17 10l-5.2 1.8L10 17l-1.8-5.2L3 10l5.2-1.8zM18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9z";
|
|
15
|
+
/** A cell's generation state (reactive), or undefined when nothing is pending or failed. */
|
|
16
|
+
export declare function aiCellState(ctrl: object, rowId: string, columnId: string): AIFieldCellState | undefined;
|
|
17
|
+
/** How many requests run at once, over every grid on the page. Default 3. */
|
|
18
|
+
export declare function setAIFieldConcurrency(n: number): void;
|
|
19
|
+
/**
|
|
20
|
+
* Generate the AI field `columnId` for records of a grid (its api, or the
|
|
21
|
+
* grid itself): 'empty' (default) the records whose cell is empty, 'all'
|
|
22
|
+
* every record the grid shows, or the records with these ids. Resolves when
|
|
23
|
+
* they are all written, failed or cancelled.
|
|
24
|
+
*/
|
|
25
|
+
export declare function generateAIField(target: unknown, columnId: string, which?: 'empty' | 'all' | ReadonlyArray<string>): Promise<AIFieldRun>;
|
|
26
|
+
/** Stop a grid's generations (of one field, or all): queued ones are dropped, running ones aborted. */
|
|
27
|
+
export declare function cancelAIField(target: unknown, columnId?: string): void;
|
|
28
|
+
/** Cells of a grid's field waiting or running. */
|
|
29
|
+
export declare function pendingAIField(target: unknown, columnId?: string): number;
|
|
30
|
+
/** One cell, from its button. Clears an earlier error first. */
|
|
31
|
+
export declare function generateAICell(ctrl: any, rowId: string, columnId: string): Promise<boolean>;
|
|
32
|
+
/** Forget a cell's error (the person edited the value by hand). */
|
|
33
|
+
export declare function clearAICellError(ctrl: object, rowId: string, columnId: string): void;
|
|
34
|
+
/** Called by each AI cell as it mounts; the returned function as it unmounts. */
|
|
35
|
+
export declare function holdAIGrid(ctrl: object): () => void;
|
|
36
|
+
/**
|
|
37
|
+
* After an edit (the grid's `cellEdited`): every AI field with `auto` on
|
|
38
|
+
* whose prompt names the edited field generates again for that record. A
|
|
39
|
+
* record whose named fields are all empty is left alone.
|
|
40
|
+
*/
|
|
41
|
+
export declare function aiFieldEdited(ctrl: any, row: unknown, columnId: string): void;
|
|
42
|
+
/** A record changed outside the grid: `BaseRemoteChange` from `<SvBase onRemoteChange>`, or one the app makes. */
|
|
43
|
+
export type AIFieldChange = {
|
|
44
|
+
/** The record's id. */
|
|
45
|
+
id: string;
|
|
46
|
+
/** The base table's id; a change to a table other than the grid's is skipped. */
|
|
47
|
+
table?: string;
|
|
48
|
+
/** 'insert' generates the record's empty AI fields; 'delete' is skipped. Default 'update'. */
|
|
49
|
+
type?: 'insert' | 'update' | 'delete';
|
|
50
|
+
/** The fields that moved, by field key. */
|
|
51
|
+
fields?: ReadonlyArray<{
|
|
52
|
+
field: string;
|
|
53
|
+
}>;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Generate the AI fields with `auto` on that changes made outside the grid
|
|
57
|
+
* set off, as an edit in the grid would: for an update, the fields whose
|
|
58
|
+
* prompt names a field that moved (unless the change wrote the AI field
|
|
59
|
+
* itself); for an insert, the record's empty ones. Only records of the table
|
|
60
|
+
* the grid shows.
|
|
61
|
+
*
|
|
62
|
+
* Nothing calls this by itself: a change made in another `<SvBase>` was
|
|
63
|
+
* generated in that page, and its value arrives as a change of its own. Call
|
|
64
|
+
* it for changes nothing generated (a server job, a script, a database
|
|
65
|
+
* console), from one page only, or every page that hears the change calls
|
|
66
|
+
* the model and writes.
|
|
67
|
+
*/
|
|
68
|
+
export declare function regenerateAIFields(target: unknown, changes: ReadonlyArray<AIFieldChange>): Promise<AIFieldRun>;
|
|
69
|
+
/** The column menu's items for an AI field (`fieldMenu`): generate the empty cells or all, or stop. */
|
|
70
|
+
export declare function aiFieldMenuItems(ctrl: any, columnId: string, def: Record<string, any> | undefined): {
|
|
71
|
+
key: string;
|
|
72
|
+
label: string;
|
|
73
|
+
icon: string;
|
|
74
|
+
separatorBefore: boolean;
|
|
75
|
+
run: () => void;
|
|
76
|
+
}[] | ({
|
|
77
|
+
key: string;
|
|
78
|
+
label: string;
|
|
79
|
+
icon: string;
|
|
80
|
+
separatorBefore: boolean;
|
|
81
|
+
disabled: boolean;
|
|
82
|
+
run: () => undefined;
|
|
83
|
+
} | {
|
|
84
|
+
key: string;
|
|
85
|
+
label: string;
|
|
86
|
+
icon: string;
|
|
87
|
+
disabled: boolean;
|
|
88
|
+
run: () => undefined;
|
|
89
|
+
separatorBefore?: undefined;
|
|
90
|
+
})[];
|
|
91
|
+
export declare const AI_FIELD_TYPE: FieldTypeDef<any>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{tick}from"svelte";import{getAIProvider}from"@svgrid/grid";import{fieldPropsOf,getFieldType,originalColumn}from"./registry.svelte.js";import{canEditField}from"./field-access.svelte.js";import{cellText,cellValue,dataRows,fieldColumns,gridOf,writeCell}from"./grid-access.js";import{aiFieldRequest,fillPrompt,promptColumn,promptRefs,readAIAnswer}from"./ai-prompt.js";import AiCell from"./AiCell.svelte";export const NO_PROVIDER="No AI provider. The app sets one with setAIProvider() from @svgrid/grid.";const NOT_EDITABLE="You cannot edit this field, so nothing was written.";const NOT_SHOWN="The record is not in the grid (filtered out or deleted).";export const AI_ICON="M10 3l1.8 5.2L17 10l-5.2 1.8L10 17l-1.8-5.2L3 10l5.2-1.8zM18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9z";const gridKeys=new WeakMap;let nextGrid=1;const gridKey=ctrl=>{let k=gridKeys.get(ctrl);if(!k)gridKeys.set(ctrl,k=nextGrid++);return k};const keyOf=(ctrl,rowId,columnId)=>`${gridKey(ctrl)}\0${rowId}\0${columnId}`;const cells=$state({});export function aiCellState(ctrl,rowId,columnId){return cells[keyOf(ctrl,rowId,columnId)]}const setCell=(key,s)=>{if(s)cells[key]=s;else delete cells[key]};const queue=[];const active=new Set;const latest=new Map;let limit=3;export function setAIFieldConcurrency(n){limit=Math.max(1,Math.floor(n)||1);pump()}const alive=ctrl=>{const el=ctrl?.scrollContainer;return!el||el.isConnected};function enqueue(ctrl,rowId,columnId){const key=keyOf(ctrl,rowId,columnId);const was=latest.get(key);if(was&&queue.includes(was))return new Promise(r=>{const prev=was.done;was.done=ok=>{prev(ok);r(ok)}});if(was)was.abort.abort();return new Promise(done=>{const job={ctrl,rowId,columnId,key,abort:new AbortController,done};latest.set(key,job);queue.push(job);setCell(key,{status:"queued"});pump()})}function pump(){while(active.size<limit&&queue.length){const job=queue.shift();if(!alive(job.ctrl)){queue.unshift(job);cancelAIField(job.ctrl);continue}active.add(job);setCell(job.key,{status:"running"});void run(job).finally(()=>{active.delete(job);pump()})}}async function run(job){const signal=job.abort.signal;try{const value=await produce(job.ctrl,job.rowId,job.columnId,signal);while(job.ctrl.editingCell&&!signal.aborted)await new Promise(r=>setTimeout(r,150));if(signal.aborted)return job.done(false);if(!alive(job.ctrl)){cancelAIField(job.ctrl);return job.done(false)}if(!writeKeepingCursor(job.ctrl,job.rowId,job.columnId,value))throw new Error(NOT_EDITABLE);if(latest.get(job.key)===job){latest.delete(job.key);setCell(job.key,null)}job.done(true)}catch(e){if(!signal.aborted&&latest.get(job.key)===job){latest.delete(job.key);setCell(job.key,{status:"error",message:messageOf(e)})}job.done(false)}}const messageOf=e=>{const m=e instanceof Error?e.message:String(e??"The request failed");return m.length>240?`${m.slice(0,240)}...`:m};function fieldOf(ctrl,columnId){const columns=fieldColumns(ctrl);const column=columns.find(c=>c.id===columnId);if(!column||column.fieldType!=="ai")return null;const props=fieldPropsOf(originalColumn(column.def));const named=columns.map(c=>({header:c.header,field:c.field,c}));return{column,props,named}}const shown=(ctrl,row,c)=>cellText(c,cellValue(ctrl,row,c),row);async function produce(ctrl,rowId,columnId,signal){const f=fieldOf(ctrl,columnId);if(!f)throw new Error("The field is no longer an AI field.");const provider=getAIProvider();if(!provider)throw new Error(NO_PROVIDER);if(!String(f.props.prompt??"").trim())throw new Error("The field has no prompt yet: write one in Edit field.");if(!canEditField(originalColumn(f.column.def),f.props))throw new Error(NOT_EDITABLE);const row=dataRows(ctrl).find(r=>r.id===rowId);if(!row)throw new Error(NOT_SHOWN);const filled=fillPrompt(String(f.props.prompt),name=>{const hit=promptColumn(f.named,name);return hit?shown(ctrl,row,hit.c):`{${name}}`});const raw=await provider(aiFieldRequest(f.column.header,filled,f.props,signal));return readAIAnswer(raw,f.props)}function writeKeepingCursor(ctrl,rowId,columnId,value){const cursor=ctrl.grid?.getState?.().activeCell??null;const range=ctrl.selectionRange;const ranges=ctrl.selectionRanges;const activated=ctrl.userHasActivatedCell;if(!writeCell(ctrl,rowId,columnId,value))return false;try{ctrl.grid?.setActiveCell?.(cursor);if(range!==void 0)ctrl.selectionRange=range;if(ranges!==void 0)ctrl.selectionRanges=ranges;if(activated!==void 0)ctrl.userHasActivatedCell=activated}catch{}return true}const ctrlOf=target=>gridOf(target)??target;const blank=v=>v==null||v===""||Array.isArray(v)&&!v.length;export async function generateAIField(target,columnId,which="empty"){const ctrl=ctrlOf(target);const f=fieldOf(ctrl,columnId);if(!f)return{written:0,failed:0};const ids=typeof which==="string"?dataRows(ctrl).filter(r=>which==="all"||blank(cellValue(ctrl,r,f.column))).map(r=>r.id):[...which];const results=await Promise.all(ids.map(id=>enqueue(ctrl,id,columnId)));const written=results.filter(Boolean).length;return{written,failed:results.length-written}}export function cancelAIField(target,columnId){const ctrl=ctrlOf(target);const mine=j=>j.ctrl===ctrl&&(columnId==null||j.columnId===columnId);for(let i=queue.length-1;i>=0;i--){const j=queue[i];if(!mine(j))continue;queue.splice(i,1);j.abort.abort();j.done(false)}for(const j of active)if(mine(j))j.abort.abort();for(const[key,j]of latest){if(!mine(j))continue;latest.delete(key);setCell(key,null)}}export function pendingAIField(target,columnId){const ctrl=ctrlOf(target);let n=0;for(const j of latest.values())if(j.ctrl===ctrl&&(columnId==null||j.columnId===columnId))n+=1;return n}export function generateAICell(ctrl,rowId,columnId){return enqueue(ctrl,rowId,columnId)}export function clearAICellError(ctrl,rowId,columnId){const key=keyOf(ctrl,rowId,columnId);if(cells[key]?.status==="error")setCell(key,null)}const drawn=new WeakMap;export function holdAIGrid(ctrl){drawn.set(ctrl,(drawn.get(ctrl)??0)+1);return()=>{const n=(drawn.get(ctrl)??1)-1;drawn.set(ctrl,n);if(n===0)setTimeout(()=>{const el=ctrl.scrollContainer;if(!drawn.get(ctrl)&&!el?.isConnected)cancelAIField(ctrl)},0)}}export function aiFieldEdited(ctrl,row,columnId){const columns=fieldColumns(ctrl);const edited=columns.find(c=>c.id===columnId);if(!edited||!row||!columns.some(c=>c.fieldType==="ai"&&c.id!==columnId))return;const id=ctrl.buildApi?.().getRowId?.(row);const gridRow=dataRows(ctrl).find(r=>id!=null?r.id===String(id):r.original===row);if(!gridRow)return;for(const ai of autoFieldsFor(ctrl,gridRow,columns,[edited]))void enqueue(ctrl,gridRow.id,ai.id)}function autoFieldsFor(ctrl,row,columns,moved){const named=columns.map(c=>({header:c.header,field:c.field,c}));return columns.filter(ai=>{if(ai.fieldType!=="ai"||moved?.includes(ai))return false;const p=fieldPropsOf(originalColumn(ai.def));if(p.auto===false||!String(p.prompt??"").trim())return false;const refs=promptRefs(String(p.prompt),named).map(x=>x.c);if(moved?!refs.some(c=>moved.includes(c)):!blank(cellValue(ctrl,row,ai)))return false;return refs.some(c=>shown(ctrl,row,c).trim())})}export async function regenerateAIFields(target,changes){const ctrl=ctrlOf(target);await tick();const table=ctrl?.props?.baseTableId;const columns=fieldColumns(ctrl);const runs=[];if(columns.some(c=>c.fieldType==="ai")){for(const change of changes){if(change.type==="delete"||table&&change.table&&change.table!==table)continue;const row=dataRows(ctrl).find(r=>r.id===String(change.id));if(!row)continue;const moved=change.type==="insert"?null:columns.filter(c=>change.fields?.some(f=>f.field===c.field));if(moved&&!moved.length)continue;for(const ai of autoFieldsFor(ctrl,row,columns,moved))runs.push(enqueue(ctrl,row.id,ai.id))}}const results=await Promise.all(runs);const written=results.filter(Boolean).length;return{written,failed:results.length-written}}export function aiFieldMenuItems(ctrl,columnId,def){if(def?.fieldType!=="ai")return[];const waiting=pendingAIField(ctrl,columnId);if(waiting){return[{key:"field-ai-stop",label:`Stop generating (${waiting} left)`,icon:AI_ICON,separatorBefore:true,run:()=>cancelAIField(ctrl,columnId)}]}const f=fieldOf(ctrl,columnId);const rows=f?dataRows(ctrl):[];const empty=f?rows.filter(r=>blank(cellValue(ctrl,r,f.column))).length:0;const locked=!f||!ctrl.editingEnabled||!canEditField(originalColumn(f.column.def),f.props);const records=n=>`${n} ${n===1?"record":"records"}`;return[{key:"field-ai-empty",label:`Generate for ${empty} empty ${empty===1?"record":"records"}`,icon:AI_ICON,separatorBefore:true,disabled:locked||!empty,run:()=>void generateAIField(ctrl,columnId,"empty")},{key:"field-ai-all",label:`Generate for all ${records(rows.length)}`,icon:AI_ICON,disabled:locked||!rows.length,run:()=>void generateAIField(ctrl,columnId,"all")}]}const PRECISION=Array.from({length:5},(_,d)=>({value:String(d),label:d===0?"1":`1.${"0".repeat(d)}`}));export const AI_FIELD_TYPE={id:"ai",label:"AI",description:"A model writes the value from a prompt that names the record's fields. Stored, and editable by hand.",icon:AI_ICON,group:"computed",width:280,defaults:{prompt:"",output:"text",auto:true,options:[]},properties:[{key:"prompt",label:"Prompt",kind:"prompt",placeholder:"Write a one-line pitch for {Name}, aimed at {Audience}",hint:"Use {Field name} for that field's value in the record."},{key:"output",label:"The model writes",kind:"segmented",choices:[{value:"text",label:"Text"},{value:"singleSelect",label:"One option"},{value:"number",label:"A number"}]},{key:"options",label:"Options",kind:"options",visible:p=>p.output==="singleSelect"},{key:"precision",label:"Precision",kind:"choice",choices:PRECISION,visible:p=>p.output==="number"},{key:"auto",label:"Generate again when a field the prompt names changes",kind:"checkbox",hint:"Off: only when someone presses the button or uses the column menu."}],fill:(d,p,ctx)=>{const as=p.output==="singleSelect"?"singleSelect":p.output==="number"?"number":"longText";const type=getFieldType(as);const props=as==="singleSelect"?{options:p.options??[]}:as==="number"?{...type?.defaults??{},format:"decimal",precision:p.precision??1}:{};return type?.fill?type.fill(d,props,ctx):{...d}},cell:AiCell};
|