Mission
User describes business logic in Vietnamese → output paste-ready JavaScript code for pageSettings.script of the layout. The target user does not know how to code → every risk (re-render loop, wiping data, idempotency) must be blocked by the skill with guards + natural questions.
Runtime API: see reference/api-cheatsheet.md.
🚨🚨🚨 RULE §0 — ABSOLUTELY DO NOT USE THE KEYWORD return (CRITICAL)
This is the MOST IMPORTANT rule of the skill. Violation = broken script.
All Layout Rule scripts are collected by the runtime into ONE single async function. If this script has return → the other scripts the user pastes below (combined from multiple sources / business logic) will BE BLOCKED from running.
ABSOLUTELY FORBIDDEN:
// ❌ SAI — chặn mọi logic phía dưới
if (!customerId) return;
const item = screen.get("address", "FORM_ITEM");
item.value = ...;
// ❌ SAI — early return dù có lý do
if (formType === "view") return;
// ❌ SAI — return trong if-else
if (type === "A") {
// ...
} else {
return;
}
ALWAYS USE if (condition) { ... } block:
// ✅ ĐÚNG — bao bằng if-block, logic phía dưới vẫn chạy
if (customerId) {
const item = screen.get("address", "FORM_ITEM");
item.value = ...;
}
// ✅ ĐÚNG — đảo điều kiện
if (formType !== "view") {
// ... logic chỉ chạy ở create mode
}
// ✅ ĐÚNG — chỉ vào nhánh khi điều kiện thoả
if (type === "A") {
// ...
} else if (type === "B") {
// ...
}
// (không có else { return; } — script tự kết thúc)
Why it is IMPORTANT
The user may paste multiple scripts from multiple sources into the same "Script configuration" box of the layout (this skill generates them + scripts the user copied from a previous task + scripts a colleague wrote). The runtime collects them all → 1 function. return in the first script = the following scripts do not run → the user has a painful debugging experience.
The only exception: continue inside a loop
// ✅ OK — continue chỉ skip iteration, không thoát script
for (const c of changedRowCells || []) {
if (c.relatedListSlug !== "order_lines") continue;
// ...
}
Applies to ALL guards
Every old guard (if (formType === "view") return;, if (!changedFields["X"]) return;, if (rows.length > 0) return;) MUST be inverted into a if (condition_đúng) { ... } block. See safety-rules.md already refactored.
🚨🚨🚨 RULE §1 — AVOID INFINITE LOOPS WHEN SETTING VALUES (CRITICAL)
This is the SECOND MOST IMPORTANT rule. Violation = browser freeze / crash, data loss, loss of user trust.
Re-trigger mechanism (MUST REMEMBER)
A Layout Rule script re-runs itself when one of the following happens:
- Any field on the form changes value (
changedFields[slug] = true) - Any cell in a related list changes value (
changedRowCellspopulate) - Layout id changes (e.g. via
screen.changeLayout(...))
→ Meaning: the script sets a value itself and is then re-triggered by that very value = INFINITE LOOP.
Typical infinite loop scenario
// ❌ SAI — vòng lặp vô tận
const totalItem = screen.get("total", "FORM_ITEM");
totalItem.value = sum;
// → value đổi → script re-run → set lại → re-run → ... → freeze
// ❌ SAI — set cell trong loop không guard
for (const row of rows) {
const priceCell = row.get("price");
priceCell.value = computePrice(row);
// → cell đổi → script re-run → loop tiếp
}
ALWAYS USE if (current !== new) { ... } BEFORE SETTING
EVERY set command .value (field or cell) MUST have a comparison beforehand:
// ✅ ĐÚNG — field cha
const totalItem = screen.get("total", "FORM_ITEM");
if (totalItem.value !== sum) {
totalItem.value = sum;
}
// ✅ ĐÚNG — cell trong related list
const priceCell = row.get("price");
const newPrice = computePrice(row);
if (priceCell.value !== newPrice) {
priceCell.value = newPrice;
}
Resetting a value to null must also be compared
// ❌ SAI — re-set null mỗi lần script chạy (vẫn loop ngầm nếu trigger khác)
applyTypeItem.value = null;
// ✅ ĐÚNG — chỉ reset khi đang có value
if (applyTypeItem.value) {
applyTypeItem.value = null;
}
Cases where NO guard is needed (safe)
| API | Trigger re-run? | Need a guard? |
|---|---|---|
field.value = / cell.value = |
✅ YES | 🚨 MANDATORY comparison |
field.limitedOptions = |
❌ NO | Optional (compare to avoid unnecessary re-render) |
field.display = |
❌ NO | Optional |
field.readOnly = |
❌ NO | Optional |
field.required = |
❌ NO | Optional |
cell.displayHtml = |
❌ NO | Optional (cosmetic) |
rl.setData(...) |
⚠️ Possible | Guard rows.length === 0 + idempotent payload |
Built-in safety net: runtime has
markParentScriptStart/End+ 200ms debounce for cell value channel — helps partially, but NOT enough to rely on. Always guard yourself.
Multi-field SET → compare each one
// ✅ ĐÚNG — mỗi field 1 so sánh riêng
if (totalItem.value !== sum) {
totalItem.value = sum;
}
if (qtyItem.value !== qty) {
qtyItem.value = qty;
}
When SET payload is complex (object/array) → shallow comparison is enough
// ✅ ĐÚNG — array of string IDs, so sánh shallow
const ids = records.map((r) => r.id);
const current = item.limitedOptions || [];
const same = current.length === ids.length && current.every((v, i) => v === ids[i]);
if (!same) {
item.limitedOptions = ids;
}
Why it's IMPORTANT
- Browser freeze → user loses data they're entering.
- React DevTools reports "Maximum update depth exceeded" → user doesn't know which script caused it.
- May not show up immediately (running 50 times / second still feels smooth on a strong machine) → you only find out after shipping to production.
- Hard to debug: stack trace only points to runtime, not to the user's script.
→ Prevent from the start with if (current !== new) is much cheaper than repeated debugging.
Supreme principle — CODE MUST BE EASY TO UNDERSTAND ON FIRST READ
User is a non-coder, and later will have to re-read / edit the script themselves. Every line of code must be readable on the very first read — you MUST NOT trade clarity for "elegance" or "smart code".
Specific rules
-
Variable names speak human language, no cryptic abbreviations:
- ✅
const orderId = $record.order; - ❌
const oid = $record.order;/const x = $record.order;
- ✅
-
Each line does 1 thing, don't cram multiple steps into 1 long expression:
- ✅ ```js
const { records } = await filterRecords("customer", { filterItems: [...] });
const customer = records[0];
const address = customer?.defaultAddress ?? "";
- ❌ ```js
const address = (await filterRecords("customer", { filterItems: [...] })).records[0]?.defaultAddress ?? "";
- ✅ ```js
const { records } = await filterRecords("customer", { filterItems: [...] });
const customer = records[0];
const address = customer?.defaultAddress ?? "";
-
Avoid nested ternaries / deep optional chaining. Break into clear if-blocks:
- ✅ ```js
if (customerId) {
const item = screen.get("address", "FORM_ITEM");
if (!item.value) { // no address yet → fill it
item.value = ...;
}
}
- ❌ ```js
screen.get("address", "FORM_ITEM").value ||
(customerId && (screen.get("address", "FORM_ITEM").value = await ...));
- ✅ ```js
if (customerId) {
const item = screen.get("address", "FORM_ITEM");
if (!item.value) { // no address yet → fill it
item.value = ...;
}
}
-
DO NOT use functional combinators (
reduce/flatMap/curry/pipe) whenfor...ofis simple enough. Users readfor (const row of rows) { ... }more easily thanrows.reduce((acc, row) => ...). -
DO NOT abstract early. A script runs only 1 business task — don't create helper functions
applyOverride(),withGuard(), factories… unless there is a mandatory reason (e.g. reused 3+ times within the same script). -
Comment explaining WHY when a guard / pass-through is not obvious:
- ✅
if (existingRows.length === 0) { /* bảng còn rỗng → mới seed, tránh ghi đè data user */ } - ✅
rl.setData(records); // records từ filterRecords đã ở API shape, pass thẳng — converter xử - ❌ Comment explaining what the code already says:
// set value vào field(redundant)
- ✅
-
Comment header
⚠️The script header is MANDATORY when there is a set value — list 3 lines: when it runs / does NOT run when / does NOT overwrite. This is the first thing the user sees when reopening the script. -
Explicit hardcode > smart config. Slug field, table slug, threshold → write them directly as string literals, don't create
const CONFIG = { ... }for 1-2 constants. -
Don't "defend" against cases that don't exist. E.g. if already
if (!orderId) return;then no need forcustomerId?.toString() ?? ""on the next line. -
Short output is better than full-but-verbose output. If the same business logic can be done in 15 lines → don't write 40 lines.
"Easy to read" test: before outputting, reread the script with the mindset of a non-coder user. If there's 1 line that must be read twice to understand → rewrite it.
Workflow (follow this exact order)
Step 1 — Read the API cheatsheet
Always Read the file reference/api-cheatsheet.md first. This is the mandatory knowledge base — do not generate code without reading it.
Step 2 — Parse the user's description
Extract 4 entities:
- Target: which field/cell/related-list (slug if the user says it; if not → placeholder + mention it in the output).
- Trigger: when the script runs (mount / changedFields / changedRowCells).
- Action: set value / show-hide / readOnly / required / submit / displayHtml / fetch.
- Pattern: seed / reactive / one-shot / aggregate / validate.
Step 2.5 — Ask for missing technical info (MANDATORY)
Script code needs the correct slug and fieldType technical details. If the user describes general business logic (e.g. "when the customer changes, fill in the address") without giving the slug/type → mandatory to ask before proceeding.
The info you must know to generate correct code:
| Info | When it's needed | Example |
|---|---|---|
| Object slug (currently configuring layout) | Always — to know which object the script runs on | return_order, order, customer |
| Field slug + fieldType | Every field mentioned in the description (target SET, trigger field, field reading data) | customer (lookup), address (short_text), quantity (number), delivery_date (date) |
| Related list slug IN THE LAYOUT | When the business logic touches a table (related list) | ⚠️ See the warning below |
⚠️ EXTREMELY IMPORTANT warning about related list slug
The slug of a related list in the layout is DIFFERENT from the slug of the linked object.
- When the designer drags a related list into the layout → they set a separate slug for that related list within this layout's scope.
- E.g.: layout
return_orderhas a related list pointing to objectorder_line, the designer sets that table's slug asreturn_order_lines(ORlines, OR whatever name the designer chooses). - In the script you MUST use the slug of the related list in the layout, not the slug of the target object (
order_line). - Wrong slug →
screen.get("order_line", "RELATED_LIST")returnsnull→ script silent fail.
When asking the user, always emphasize:
"What is the slug of the related list in the layout ? This is the slug the designer set when dragging the table into the layout. Go to the Edit interface page → click on the table → check the 'slug' field. It is NOT the slug of that other object."
Asking pattern (combine into 1 time if missing lots of info)
Use AskUserQuestion with 1-3 questions (each question covers 1 cluster of info), OR ask text directly with a checklist:
Để sinh code chính xác, cho mình biết các slug và type:
1. **Object** đang config layout: slug là gì? (vd: `return_order`)
2. **Field "khách hàng"**: slug? fieldType? (vd: slug=`customer`, type=`lookup`)
3. **Field "địa chỉ"**: slug? fieldType? (vd: slug=`address`, type=`short_text`)
4. **Bảng "chi tiết đơn"**: slug **TRONG LAYOUT** là gì? ⚠️ KHÔNG phải slug của object kia.
(Vào Sửa giao diện → click vào bảng → xem field 'slug')
If the user answers incompletely → ask again for exactly the missing item. Do NOT guess the slug. Do NOT use the placeholder /* SLUG */ anymore — there must be a real slug or stop the workflow.
Step 3 — Detect DANGER MODE (MANDATORY)
If the description has 1 of the following keywords → go into DANGER MODE:
- "set", "assign", "change value", "fill", "auto-fill"
- "take from X and pour into Y", "copy", "duplicate", "get data"
- "seed", "auto-save", "submit"
- "when X is selected then set/change/fill Y"
→ Open reference/safety-rules.md + go through the Decision tree below. Do not skip even if the description seems complete.
If the description does NOT have set value (only show/hide/readOnly/highlight) → skip the decision tree, go straight to Step 5.
Step 4 — Decision tree (only when DANGER MODE)
Use AskUserQuestion to ask the following 3 questions in order. Option format must have a concrete Vietnamese example, do not use technical terms:
Q1 — When should it run?
Header: "When to run" Question: "When should this script run?" Options:
- "When the user just opens the form" — Example: as soon as the form is opened the script runs, whether it is a new form or a saved form.
- "When the user has just created a record" — Example: only runs on the Create new page, does NOT run when opening a saved form to view/edit.
- "When the user changes 1 specific field" — Example: when the user changes the 'Customer' field → auto-fill the address. The field name will be asked in the next question.
- "When the user types into a field in the table" — Example: when the user types into the 'Product name' field in a row → auto-fill the 'Price' field in the same row.
Q2 — Re-run on edit? (ONLY ask if Q1 = option 1)
Header: "Opening a saved form" Question: "When the user reopens a previously saved form to view/edit, does the script need to run again?" Options:
- "Do NOT need to re-run (safest)" — Example: Return Order form already saved, user opens it to view → do NOT auto re-seed order_lines, keep the saved data as is.
- "Needs to re-run" — Warning: only select when you are certain you want to overwrite, may delete changes the user has made.
Q3 — Overwrite policy?
Header: "Overwrite data" Question: "Before the script changes the value, might the target (cell or table) already have data entered by the user?" Options:
- "May have — must NOT overwrite" — Example: order_lines table may have rows the user added themselves, the script must not delete them.
- "Definitely empty — overwrite is fine" — Example: an automatic field is always empty initially, filling in a new value is no problem.
- "Always overwrite" — Warning: will delete data the user entered manually if any. Only select when the business requires a reset.
Q4 (optional follow-up) — Name of trigger field/cell (ONLY when Q1 = 3 or 4 and the user hasn't provided the slug)
Ask directly with text (no AskUserQuestion):
- Q1=3 → "What is the slug name of the field the user changes?" (e.g.
order,customer) - Q1=4 → "What is the table slug + cell slug?" (e.g. table
order_lines, cellproduct)
Step 5 — Map answers → recipe + guard variant
Read reference/recipes.md to choose the recipe. Apply guards per the table (from safety-rules.md).
⚠️ REITERATE RULE §0: ABSOLUTELY DO NOT use
return. Every guard below uses anif (positive_condition) { ... }block surrounding the logic, DO NOT useif (negative_condition) return;.
| Q1 | Q2 | Q3 | Guard wrapper (if-block) |
|---|---|---|---|
| 1 every time it opens | 1 no re-seed | 1 no overwrite | if (formType !== "view") { if (rows.length === 0) { ... } } + (optional) $ref.seeded |
| 1 every time it opens | 1 no re-seed | 2 definitely empty | if (formType !== "view") { ... } |
| 1 every time it opens | 2 with re-seed | 3 always overwrite | banner ⚠️ — run directly, no guard needed |
| 2 create new only | n/a | 1 no overwrite | if (formType !== "view") { if (rows.length === 0) { ... } } |
| 2 create new only | n/a | 2 definitely empty | if (formType !== "view") { ... } |
| 3 user changes field X | n/a | 1 no overwrite | if (changedFields["X"]) { if (!target.value) { ... } } |
| 3 user changes field X | n/a | 2 definitely empty | if (changedFields["X"]) { ... } |
| 3 user changes field X | n/a | 3 always overwrite | if (changedFields["X"]) { ... } + ⚠️ banner |
| 4 user types in cell | n/a | any | for (const c of changedRowCells || []) { if (c.relatedListSlug === "X" && c.fieldSlug === "Y") { ... } } — DO NOT use continue unless the loop body has multiple steps |
Step 6 — Generate code with guard + compare before set
⚠️ REITERATE RULE §0: ABSOLUTELY DO NOT use
return. Wrap the entire logic withif (positive_condition) { ... }block.
Every parent field set value must be accompanied by a comparison:
const item = screen.get("X", "FORM_ITEM");
if (item.value !== newValue) {
item.value = newValue; // tránh re-render loop
}
Every rl.setData(...) must check existingRows.length === 0 (with an if-block) unless Q3=3.
Header comment automatically (auto-prepend when DANGER MODE is present):
/**
* ⚠️ SCRIPT NÀY THAY ĐỔI DỮ LIỆU FORM TỰ ĐỘNG
*
* Chạy khi: <Q1 answer>
* KHÔNG chạy khi: <Q2 logic>
* KHÔNG ghi đè: <Q3 logic>
*
* Nếu sửa script này, GIỮ NGUYÊN các điều kiện `if (...)` bao quanh logic.
* TUYỆT ĐỐI KHÔNG thêm `return` — script này nằm chung 1 hàm với
* các script khác, `return` sẽ chặn chúng không chạy.
*/
Step 7 — Verify checklist before output
Self-check 10 points:
- 🚨 ABSOLUTELY NO keyword
returnanywhere in the script (including inside if-else, including "for a good reason"). The script runs in the same function as other scripts —returnblocks everything. Grep the code you just generated to see if there isreturn. If YES → fix by wrapping in an if-block. The only exception:continueinside aforloop. - 🚨 EVERY SET
.value(field or cell) MUST haveif (current !== new) { current = new; }— RULE §1. Re-triggering the script is automatic → setting a value without a guard = infinite loop. Grep the code: find every line containing.value =(includingfield.value,cell.value,item.value,row.get(...).value) → immediately check whether there isif (... !== ...)above it. Settingnullmust also compareif (item.value) { item.value = null; }. - Does every
rl.row/rows/findRow/submit/filterRecordshaveawaityet? - Does the Value SET for
row.get(slug).value/field.valuematch §7 SCRIPT shape ? (date →Date, time → ms, range →{ gte, lte }, lookup → string ID — NOT{ id, ... }) rl.setData(records)does it use §7B API record shape ? (date → epoch ms number — NOTDateobject; lookup → acceptsRecordItem | string | array). Do NOT confuse the 2 shapes.- Does SET table have guard
if (rows.length === 0) { rl.setData(...) }(unless the user chose overwrite)? Is the setData payload idempotent (same input → same output)? - Is the guard wrapper from Step 5 table present? (if-block, NOT
if (...) return;) - NO self-cache of type
if ($ref.xxx) ...; / $ref.cached = await filterRecords(...).filterRecordsalready has React Query cache built-in — wrapping it is redundant = junk code + stale data. - Code is easy to read at first glance (see "Supreme principles" at the top of the file): variable names sound human, one task per line, no nested ternaries, no redundant helper functions, no premature abstraction, no "defensive" handling for cases that do not exist. Re-read the script with a non-coder user's mindset — if you have to read a line a second time to understand it → rewrite it.
changeLayout/triggerButtondoes it have a loop guard? (e.g.if ($ref.lastLayout !== id) { ... }for changeLayout)
Error → fix in-place. Do not output code that has not passed 10/10. Score 0 or a wrong point 1 = REJECT the entire code.
Step 8 — Output
MANDATORY format (4 parts):
## Code
[code block JavaScript đầy đủ — paste vào ô Cấu hình script]
## Script này làm gì
[3-5 dòng tiếng Việt thân thiện: chạy khi nào, kiểm tra gì, đổi gì, có gì để bảo vệ data user]
## 🧪 Bắt buộc test trước khi đưa lên production
1. [test case 1 cụ thể với business]
2. [test case 2]
3. [test case 3]
4. [test case 4 — chú ý edge case Q2/Q3 user đã chọn]
## 📖 Thuật ngữ trong code
[Glossary cá nhân hoá: CHỈ in những thuật ngữ thực sự xuất hiện trong code lần này. Tra từ Glossary Dictionary bên dưới.]
Glossary Dictionary (for the skill to look up when building output)
When outputting, scan the code you just generated, only print entries matching words that appear:
| In code | Vietnamese explanation |
|---|---|
changedFields["X"] |
"user just changed field named X" (true/false) |
changedRowCells |
"list of table cells the user just typed" (array) |
await |
"wait" — placed before a function that must finish before continuing |
$record |
"the record being edited" — contains the values of the fields |
$record.id |
"ID of the record" — if present it means the form has already been saved |
formType |
"type of form currently open" — "create" = Create new, "view" = saved (view/edit) |
$parentRecord |
"parent record" — when a child form (modal/related list) |
$currentPersonnel |
"the employee currently logged in" |
$ref |
"script's temporary memory" — persists across script re-runs within 1 session |
screen.get(slug, "FORM_ITEM") |
"get field with slug = X" |
screen.get(slug, "RELATED_LIST") |
"get table (related list) with slug = X" |
screen.changeLayout(id) |
"switch to another layout" |
screen.triggerButton(slug) |
"automatically click button with slug = X" |
field.value |
"value of the field" — readable and writable |
field.display = false |
"hide the field, do not display it" |
field.readOnly = true |
"lock the field, do not allow editing" |
field.required = true |
"make this field required" |
field.limitedOptions |
"limit selectable options (for select)" |
rl.setData([...]) |
"overwrite all rows in the table with a new record array (per API record shape — see §7B cheatsheet, DIFFERENT from SCRIPT shape of row.get().value)" |
rl.rows() |
"get the list of existing rows in the table" |
rl.row(i) |
"get row i (0 is the first row)" |
rl.findRow(predicate) |
"find 1 row by condition" |
rl.submit() |
"automatically save the table — no need for the user to click the Save button" |
row.get(slug) |
"get cell with slug = X in the row" |
cell.displayHtml |
"change how the cell is displayed (visual only, does not save data)" |
filterRecords(slug, params) |
"query the list of records from another object" |
isDirtyForm |
"whether the form has unsaved changes" |
new Date() |
"current date and time" |
Reference files
| File | When to read |
|---|---|
reference/api-cheatsheet.md |
ALWAYS — Step 1 |
reference/safety-rules.md |
When entering DANGER MODE — Steps 3+5 |
reference/recipes.md |
Step 5 — choose template |
reference/case-studies.md |
When the user's description matches an existing case study (e.g. "set order_line from order") — read to clone the pattern |
Anti-patterns (FORBIDDEN)
- 🚨 USE
returnIN SCRIPT — EXTREMELY SEVERE. Script Layout Rule runs in the same async function as other scripts the user pastes in.returnin this script → blocks all logic below (including scripts written by colleagues, scripts copied from other tasks). ALWAYS useif (positive_condition) { ... }block. Only exception:continueinforloop. See RULE §0 at the top of the file. 0.5. 🚨 SET.valuewithoutif (current !== new)guard — CREATES AN INFINITE LOOP. Re-triggering the script is a built-in mechanism: every time a field/cell value changes → the script runs again. Setting a value without comparing → infinite loop → browser freeze. Applies to everyfield.value =,item.value =,row.get(...).value =,cell.value =. See RULE §1 at the top of the file. - Generating code without fully knowing the slug + fieldType + related list slug. Guessing = wrong. Always ask.
- Confusing the related list slug in the layout with the target object slug. Must remind the user "the slug in the layout, not that other object" every time you ask.
- Generating code without asking Q1/Q2/Q3 when the business logic has set value. Even if the user describes it in detail, you still must ask to confirm intent.
- Omitting the comment header
⚠️when the script has set value. A user maintaining it later won't know why the guard exists. - Output code missing a test checklist. The user needs to know what to test.
- Setting the parent field value without
if (item.value !== ...). Triggers a re-render loop. - rl.setData without
rows.length === 0unless the user chooses explicit overwrite. - Using technical terms in questions. The user is a non-coder. Always say "when the user opens the form / when the user changes a cell" instead of "trigger", "mount", "changedFields".
- Generating > 1 script in the same output. 1 turn = 1 script. If the user describes 2 business logics → ask whether to split or merge.
- Self-caching the result of
filterRecordsinto$ref(e.g.if ($ref.products) return;,$ref.cached = await filterRecords(...)).filterRecordsalready has React Query's built-in cache — calling again with the same params = cache hit. Self-cache = redundant code + stale data.$refis only used for real script state (seeded,submitted, counter, last-layout-id to prevent swap loop). - Confusing the shape of
rl.setData(records)with the SCRIPT shape thatrow.get().value.setDatareceives API record shape (§7B):date= epoch ms number,lookup=RecordItem | string | array.row.get().valuereceives SCRIPT shape (§7):date=Date,lookup= string ID. Don't passnew Date(...)for a date field in setData → blank. Default: if the records come fromfilterRecords→ pass them straight through, do NOT map manually. - "Clever" code that's hard to read — cramming many steps into 1 long expression, nested ternaries, optional chaining 4+ levels deep, using
reduce/flatMap/curry whenfor...ofis enough, creating a helper function used only once, abstracting early (factory, hooks-style in a script), cryptic abbreviated variable names (oid,c,x). A non-coder user won't understand it, can't fix it, and the business breaks. See "Supreme principles" at the top of the file.