<script setup>
import { Effect } from "effect";
import { customRef } from "vue";
import { cel as _rawCel } from "../../utils/cel";
import { celBindings, injectCELContext, provideCELContext, provideScopeAddress } from "../../utils/cel-context";
import { provideSelectionsRegistry } from "../../utils/selections-registry";
import { useDerived, useDerivedQuiescence } from "../form/utils/derived";
import { provideFormState } from "../form/utils/state";
defineOptions({ name: "ShwfedTableRowProvider" });
const props = defineProps({
  sourceIndex: { type: Number, required: true },
  displayIndex: { type: Number, required: true },
  derivedColumns: { type: Array, required: true },
  getRow: { type: Function, required: true },
  setRow: { type: Function, required: true },
  scopeId: { type: String, required: false }
});
const rowRef = customRef((track, trigger) => ({
  get() {
    track();
    return props.getRow(props.sourceIndex);
  },
  set(next) {
    props.setRow(props.sourceIndex, next);
    trigger();
  }
}));
const selections = provideSelectionsRegistry();
provideCELContext({
  row: {
    type: "dyn",
    label: "\u5F53\u524D\u884C",
    description: "\u5F53\u524D\u884C\u7684\u6574\u884C\u6570\u636E\uFF1B\u5199\u5165\u5F0F\u7F16\u8F91\u5217\u53EF\u7ECF `useFormState().setAt` \u89E6\u53D1\u5176\u53D8\u5316\u3002",
    value: () => rowRef.value
  },
  index: {
    type: "number",
    label: "\u884C\u5E8F\u53F7",
    description: "\u5F53\u524D\u884C\u5728\u6240\u6709\u6570\u636E\u4E2D\u7684\u5E8F\u53F7\uFF0C\u4ECE `0` \u5F00\u59CB\u3002",
    value: () => props.displayIndex
  },
  selections: {
    type: "dyn",
    label: "\u9009\u4E2D\u9879",
    description: "\u672C\u884C\u5404\u9009\u62E9\u5217\u5F53\u524D\u9009\u4E2D\u9879\u7684\u5B8C\u6574\u5BF9\u8C61\uFF08\u6309\u5217\u6807\u8BC6\uFF09\u3002",
    value: () => selections.entries.value
  }
});
if (props.scopeId) {
  provideScopeAddress(props.scopeId, {
    row: () => rowRef.value,
    index: () => props.displayIndex
  });
}
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const formState = provideFormState(rowRef, "row");
useDerived({
  fields: () => props.derivedColumns,
  evaluate: (expression) => $cel(expression),
  ready: Promise.resolve(),
  formState,
  quiescence: useDerivedQuiescence()
});
defineExpose({ evaluate: (expression) => Effect.runSync($cel(expression)) });
</script>

<template>
  <slot />
</template>
