@joplo-app/plugin-content 0.6.2 → 0.7.1
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/guide.d.ts +2 -2
- package/dist/guide.js +42 -6
- package/dist/plugin.d.ts +29 -1
- package/dist/plugin.js +47 -8
- package/dist/runtime.d.ts +28 -0
- package/dist/runtime.js +221 -12
- package/dist/version.json +1 -1
- package/package.json +2 -2
package/dist/guide.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const skill = "# Joplo content production: content\n\nFor explainers, tutorials, science and news-explainer pieces that should feel like a good video, not a deck: the viewer watches a world change while a voice explains it.\nAuthor one standalone work in works/<key>.tsx with work(); put chapter() slices under scenarios and narrate() in their steps. Chapters continue in declaration order by default. Works have covers and enter the project home page; no feature, review cases or pick is needed. Full example: examples/llm-explainer.\n\nInstall @joplo-app/plugin-content at the Joplo version; import content and add it to config.plugins. Import { Canvas, camera } from this package; keep work, chapter, patch, narrate and hold from @joplo-app/kit. Use theme: 'content:studio' for the bundled CSS. No plugin is implicitly enabled.\n\n## Minimal work\nIn a project with content enabled in config.plugins (and the starter's type: module / JSX tsconfig):\n```tsx\n// works/explainer.tsx\nimport { work, chapter, narrate } from '@joplo-app/kit';\nimport { Canvas } from '@joplo-app/plugin-content';\nexport default work({ title: 'A request in motion', summary: 'Follow one request',\n stage: <Canvas w={1280} h={800} />,\n scenarios: {\n arrival: chapter('A request arrives', { expected: 'Understand where it starts' })\n .system('Arrive', narrate('A request arrives.')),\n response: chapter('The worker responds').system('Respond', narrate('The worker replies.')),\n },\n});\n```\nThis is the authoring skeleton; add a visible subject and real changing state before reviewing the film. stage/layers needs no routes/ directory. Use on/routes explicitly when reusing product pages. WORK_INVALID means repair the required fields or slice builders; WORK_SLICES_MIXED means use chapter() consistently; FROM_UNKNOWN lists valid keys; WORK_EMPTY means add your first slice. Keep render/deep-link ids from outline --format json (standalone: explainer.arrival; feature-attached: queue.a.waiting), while --work takes the public entry key.\n\n## 1. Before TSX: package and plan within the agreed scope\n- One thing the viewer should be able to repeat afterwards, in one sentence.\n- Package first: the title asks the question; a thumbnail line of at most five words gives the surprising answer (complement the title, never repeat it); chapter('Slice title', { description }) is the cover sentence. The share preview is the first scenario's first frame, so design that frame as a thumbnail: one big line, one focal object, high contrast.\n- If the framing is unresolved, offer two or three devices (one running example, misconception then correction, a number made tangible, before and after) with a recommendation. Reuse an already agreed design; do not repeat approval rounds the user has waived.\n- Chapters: one question per chapter. Chapter titles are questions ('What does it actually read?'); the UI adds their numbers automatically. chapter('Slice title', { expected }) is what the viewer can now say. List every point from the source material and map each to a chapter or drop it on purpose.\n- One running example through every chapter (the same prompt, person, or data set), so each chapter builds on what the viewer already saw.\n- Write the script as one line per step: ears (narrate), eyes (what changes on stage), source. Adjacent steps should connect with 'but' or 'so'; a chain of 'and then' is flat.\n- Budget: narration reads about 4.5 CJK characters (2.5 English words) per second; 45\u201390 s per chapter. About 400 CJK characters can already exceed 90 seconds. npx joplo outline counts narration in its estimates.\n\n## Asset-first preparation\nBefore building a device, historical interface or illustrated object, make an asset list. Prefer a suitable licensed library, icon set or model; do not hand-write complex SVG or build a model merely because JSX can draw it. Verify the actual asset license, collect files in assets/, retain licenses and record author, URL and modifications in assets/SOURCES.md. Historical facts and historical appearance are separate evidence: label stylized reconstructions and invented messages, and avoid copied logos/system icons. Use original work only when a suitable reusable asset is unavailable, keeping it simple.\n\n## 2. Hook (first chapter, 20\u201335 s)\n- Beat 1: a familiar scene that pays off the thumbnail. Never a logo, an agenda, or a definition first.\n- Beat 2: the twist, shown on stage (the answer splits into pieces with probabilities, a name changes on the second try).\n- Beat 3: pull back and name the questions the episode answers. Pin each question where it will be answered, and close every loop later.\n\n## 3. Not slides: one world, continuous objects, a moving camera (the core)\nFailure mode, even with nice graphics: one board per chapter (big title, panels, footer), chapter title cards, cards of bullets, things fading in and out. Viewers read it as a deck. Instead:\n- One layer holding one <Canvas w={2560} h={1600}> world (the default view is 1280\u00D7800, scaled to fit, never re-laid out; in a container without a height it sizes itself from the view ratio, and render warns 'Canvas has no size' if it still has none). Place a few containers absolutely in design pixels; lay out inside them with flex.\n- Objects keep their identity: give each one motion=\"key\". Write each arrangement as static JSX switched with when, reusing the same key; between steps Joplo flies the object from its old place and size to the new one, also across containers. Morph, never replace: the question's words split into tokens, flip into ids, then fly onto a tape; bars rearrange into a lottery strip.\n- shot() draws the host focus ring and caps UI zoom at 1.25\u00D7; use camera() for traveling inside a Canvas without that ring.\n- When another plugin effect also suggests host focus (for example a diagram trace inside a Canvas), use an explicit shot() for the whole director layer if the Canvas camera should own the framing. Otherwise host zoom and Canvas zoom can multiply and push nearby text out of view. Verify the actual visible bounds in playback, not only DOM text.\n- Camera: camera('id', \u2026) frames those elements (Joplo measures them, adds pad, caps zoom); camera() shows the whole canvas. Establish wide, push in on detail, pull back for the payoff. Object flights in the same step follow the camera's timing, so both land together.\n- Chapters continue: chapter() starts from the previous chapter's last frame (state, camera, director layer) by default. Only use from: null to restart, or from: 'sliceKey' for another predecessor; keep all slices chapter() within this work. patch($.ui, { \u2026 }) changes several values in one step.\n- System-only chapters stay on the initial director layer unless camera(), shot(), a cue, or chapter('Slice title', { layer }) selects another layer. Continuing from a chapter inherits its final layer; do not copy its state by hand.\n- screen children of the Canvas stay fixed on screen: chapter label, source line, poster, end card.\n- Takeaways land on objects (a pinned question flips to '\u2713 answer'); the recap is a pull back to the whole world. Use .card() only when nothing on stage can carry the moment.\n```tsx\n<Canvas w={2560} h={1600}>\n <div id=\"tape\" style={{ position: 'absolute', left: 120, top: 960, display: 'flex', gap: 8 }}>\n {IDS.map((t, i) => <span when={eq($.ui.at, 'tape')} motion={`tok_${i}`} style={{ background: COLORS[i] }}>{t}</span>)}\n </div>\n <div screen style={{ position: 'absolute', left: 20, top: 16 }}>{$.ui.chapter}</div>\n</Canvas>\nchapter('What does it read?')\n .system('Split', 'Nine characters, seven pieces', patch($.ui, { mode: 'split' }), camera('bubble', { pad: 160 }))\n .system('To the tape', 'It reads these numbers', patch($.ui, { at: 'tape' }), camera('tape', 'meter'))\n```\n- Anti-deck test: three or more steps that only show or hide whole panels, or a frame that is mostly text, means rebuild those steps as objects that move or change.\n\n## 3b. Transitions, drift and the safe area\n- enter / exit on any element inside the Canvas (world or screen layer): fade, rise, zoom, shrink, wipe, iris. Timing: enterMs / enterDelay / exitMs / exitDelay (0\u201310000 ms literals; defaults 600 / 450). Each preset is an \"away\" pose: enter goes away \u2192 the element's own look, exit goes own look \u2192 away. So rise enters from below and exits sinking back; zoom lands from slightly larger and exits flying toward the camera; shrink grows from smaller and exits receding; wipe reveals left \u2192 right; iris opens from the centre. Set transform-origin in CSS to say where zoom/shrink grow from (a menu from its taskbar, a bubble from its tail).\n- enter plays when an element first appears (a new DOM node) during playback; exit plays when when becomes false: a non-interactive ghost copy keeps the last look and animates out, then disappears. Put enter + exit on two exclusive siblings in the same step for a crossfade. A same-motion-key element that flies (FLIP) never also enters or leaves.\n- Pick by meaning: fade for a whole-world swap under cover, rise for things that come from below (menus from a taskbar, keyboards, receipts), shrink for windows opening, zoom for something punching toward the viewer, wipe for typed/printed results, iris for a reveal from a point. Keep two or three per piece; do not give every element the same entrance.\n- camera(\u2026, { drift }) keeps the camera moving after it lands: a number = zoom factor reached over ms (default 8000), or { zoom, x, y, ms } with x/y in design px; false stops it. <Canvas drift={\u2026}> sets the default for every step; without either, a subtle 4 % / 8 s push applies. Drift eases in and out and stops at its end point; it freezes on pause, records in video, and screenshots/deep links show the settled frame without drift. The next camera move starts from where the drifting camera actually is, including when only drift changes or is switched off; the configured camera ms eases back to the target before the next drift.\n- <Canvas safe={[top, right, bottom, left]}> (design px) is the part of the view your screen-layer chrome covers. Targeted camera() frames fit inside the rest, and drift zooms around its centre; camera() with no ids still shows the whole world full-bleed.\n- UI life inside one interface (a caret blink, a stepped menu drop) can be CSS @keyframes in the project theme: the engine clock samples them, pause freezes them, static frames show their end state.\n\n## 4. Choose the information shape, then the picture\n- A number landing; before and after; ranking (bars from zero, length proportional); part of a whole (a strip whose segment widths are the shares); a process (one object going around a loop); misconception then fact; a timeline; a place (tiles or a simple map).\n- Similar sentences get different pictures. Labels sit on the thing they name; no legends when a direct label fits.\n- Compute numbers in TS from one source (for example probabilities from one set of scores) so every number on screen agrees. Label illustrative numbers on screen ('illustrative'), separate from sourced facts.\n\n## 5. Motion and layout numbers\n- Camera moves 1\u20131.5 s, ease in-out. Object flights 0.9 s ease-out; stagger 60\u2013120 ms (motionDelay); slow a landing pointer to 1.5\u20132 s (motionMs).\n- One primary motion per step; text that is being read does not move.\n- Entrances and exits: use enter / exit (section 3b); for effects the presets do not cover put @keyframes and classes in themes/<name>.css and use className (staggered with animationDelay). Screenshots, thumbnails, and jumps show the end state. For a typewriter reveal give each character a short linear fade (about 80 ms) with its own delay; a 1 ms steps(1) animation can stay stuck invisible in Chromium.\n- One accent color with a fixed meaning; color means the same thing in every chapter.\n- Size text for the frame you show: about 28 design px is the floor at 1\u00D7 zoom; a wide shot at 0.5\u00D7 needs 40 or more, or enlarge the labels for that shot (a bigger variant under the same motion key).\n- Frame by content (camera ids), not by guessed coordinates. Lay the world out as shot-sized clusters of roughly 16:10 (a machine with its output bars and strip, a chat with its bubbles); a cluster much wider than that leaves half the frame empty however you aim.\n- Same subject, same frame: keep one camera for consecutive steps about the same cluster; frame what stays on stage (not a container that has just emptied).\n\n## 6. Narration, captions, numbers\n- Caption: what the eye needs, ideally at most 16 CJK characters (24 is the hard limit). narrate(): what a presenter says, one or two sentences (rules: story section 6).\n- One number per step, rounded and written as spoken; translate numbers ('one chance in 365'). Pointing words are fine ('look at the dashed line').\n- When narration is on, keep on-stage text to labels; do not put the narrated sentence on screen too.\n\n## 7. Facts and sources\n- All facts in one data module with source and date; a source line (screen element) per chapter; name studies in narration ('OpenAI, in a 2025 paper, explains \u2026').\n- Say only what the source says. Bars start at zero. Separate illustrative values from facts on screen.\n- Images: licensed or public domain, credited, CREDITS file next to them (story section 7).\n\n## 8. Ending\n- Pull back to the whole world: every pinned question now shows its answer. Then one concrete action the viewer can take right away, as a screen element. Stop once the value lands; no 'thanks for watching'.\n\n## 9. Required: review before handing over\n- npx joplo check until 0 errors, then npx joplo outline --work <key>: verify the chapter order, step counts and estimated duration. Standalone works do not run feature coverage or HAPPY_PATH_ONLY checks.\n- Storyboard every chapter: npx joplo render --scenario-id <id> --sheet --out board.png prints every step in one image with its caption and narration. Read it frame by frame and assume the first one has problems: half-empty frames, objects cut at the edge, labels overlapping, text too small in wide shots, the chapter label covering content. Fix, then storyboard again.\n- Film-strip every chain of chapters: npx joplo render <dir> --scenario-id <first> --film --chain --out film.png. Fix every red CUT (one-frame full-screen change) unless it is your one deliberate cut, and every grey STILL (no visible change for \u2265 1.5 s). The storyboard cannot show either. Engine checklist: npx joplo skill demo, \"Make it play like a film\".\n- Play each chapter in the board with Voice on: flights and camera land together, nothing leaves the frame mid-flight, narration finishes before the next step.\n- Evidence, not belief: 'it plays' needs check 0 errors plus a run in the board; 'it looks right' needs the rendered frames; 'it is clear' needs captions-only and frames-only passes that both tell the story.\n- Tell the user what you could not verify (a real voice on a phone, other window sizes).\n\n## Migrating an existing script safely\n- Freeze the previous dev IR before moving files. Compare all steps, plugin drawing/media snapshots and every stateAt position after migration; a flow-to-chapter rename does not prove the same continuous state, motion or sound.\n- A chapter that previously began independently needs from: null. Default continuation carries the previous ui/data/inputs and running music; use it only when the next chapter should inherit that ending.\n- Put audience descriptions from feature.roles into audience. Preserve real role() speakers, the role keys used by say(), and config.voice.roles together; verify the chosen voices in playback.\n- If the project already has a helper named chapter, rename that helper before importing chapter from the kit.\n- Remove manual numbering from the chapter title itself, not every identical string. A transition card or caption may still use the old source text; let i18n missing/stale/unused diagnostics determine which translation keys need changing.\n- Inspect a path page before deleting it. A Slot-only/empty wrapper can be removed for stage/layers; reuse actual picture content through explicit on or the work's routes.\n- To prove a draft did not publish, search all build artifacts for one complete sentence unique to the old work and absent as a substring of current copy. Keep the old work locally with draft: true; do not rely on the published menu alone.\n\n## Diagnostics and recovery\n- CAMERA_UNKNOWN: the id must exist in a current layer or stage; frame elements inside this Canvas. CAMERA_INVALID: pad 0\u20132000, zoom 0.1\u201310, ms 0\u201310000, drift false | 0.5\u20132 | { zoom 0.5\u20132, x/y \u22122000\u20132000, ms 500\u201360000 }, finite numbers only; <Canvas drift> takes the same values and <Canvas safe> is four numbers 0\u20132000.\n- PLUGIN_PROPERTY_INVALID: motion is a nonempty string; motionDelay/motionMs/enterMs/enterDelay/exitMs/exitDelay are finite numbers 0\u201310000; screen is boolean; enter/exit are one of fade, rise, zoom, shrink, wipe, iris. These universal properties are literals, not state bindings. Use separate same-key elements with when for a flight between containers.\n- Exit ghosts appear only during playback, never in screenshots, thumbnails, deep links, reduced motion or after a jump. They settle instantly (enter jumps to its end, ghosts vanish) on a jump, stop, scene change and the viewer's first input on the stage (a click, key or drag; the player's pause button keeps them frozen), so the input always acts on the final picture. The camera does not settle on input: it freezes where it is. Ghosts carry no id: camera, hints and Alt-click never target them.\n- Known limits (0.3.0): put exit on the removed container itself \u2014 an exit only on a child of a removed, transformed (scaled) container loses that ancestor's transform for its first frame. An element removed while its enter is still running exits from its base look (a small jump): keep enter shorter than the step. Two elements sharing a motion key with the same layout get neither enter nor exit: use different keys, or change the layout so a flight happens.\n- Give each visible object one motion key. Hidden previous locations remain available for a later same-key arrival. Avoid duplicate simultaneously visible keys. Independent translate/scale keeps the author's transform intact.\n- Cross-container flights temporarily lift clipping ancestors inside the world and restore their overflow at finish/cancel. During playground edits the flight yields its visual transform to the final usable layout while preserving its animation/time anchor for resume. Do not globally remove device clipping or duplicate the animated control to make it clickable; test first input during a flight.\n- Keep camera and FLIP duration together when both move; motionMs explicitly overrides duration, including 0. animate=false cancels an existing flight and renders the final layout.\n- A Canvas with no parent height uses its view aspect ratio; with an explicit parent height it fills that parent. A zero-sized parent still needs a layout fix; render reports the measured surface.\n- screen only separates direct Canvas children into the fixed overlay. Nested screen props remain ordinary descendants.\n- One world per continuous chapter; use chapter() default continuation to avoid manually copied end states. The initial frame and every step contain complete compiled drawing snapshots; deep links do not replay plugin logic.\n- HAPPY_PATH_ONLY belongs to feature review. If an explainer receives it, move the piece to works/<key>.tsx with work()/chapter() and remove its artificial cases; do not invent product failures. Review every storyboard and verify animation separately from static renders.\n";
|
|
2
|
-
export declare const patterns = "# content recipes and pitfalls\n\n## Museum-film composition\n- Collect licensed artwork and a real subject asset first. Let an archival image supply the historical texture and the subject supply the action; use CSS only for framing, gradients and typography. Label illustrative artwork when it is not evidence of the place or event.\n- Put the Canvas inside a wrapper with an explicit height (for a board-filling root, height:100%). An auto-height wrapper can remain 800px tall while the board is shorter: exports look correct but lower controls are clipped. Test the actual board at a short height as well as render.\n- Keep chapter/source labels as direct screen children when the world camera travels. Nested screen does not escape its parent. Frame a stable hero cluster with a modest pad; an oversized pad may zoom out and expose empty margins instead of producing a close-up.\n- For a subject entering a device, establish the device first or in the same step, then shrink and move the subject into its screen. Keep the ending actionable through real forks or controls. Reuse the stable subject identity described below.\n- Match-cut the subject at a chapter boundary while changing its background and sound in that same scripted step. The input stays concrete: click the object, drag it to a visible destination, or choose an explicitly labeled branch. Avoid a slide of historical bullet points.\n\n## Shot grammar for a playable short film\nGive each chapter a visual arc: establish the whole interface/device, move in on the meaningful input or action, show its result, then pull back. Keep chapter numbers and explanations subordinate to the working surface. Judge text at its final painted size, including Canvas scale and camera zoom, rather than the font-size declaration alone.\n\nUse camera ids for the object that matters. Framing a wide window rarely produces a button close-up; frame the button for anticipation and button plus receipt for the result. Keep those targets inside one visual cluster. A deliberate crop is useful; a required action cropped out of the current frame is a broken shot.\n\nWhen a whole-stage camera would collide with navigation or titles, either put Canvas in a separately sized parent whose view matches the picture region (controls stay in the surrounding layout), or go full-bleed: put the title and timeline on the screen layer over the moving picture and give <Canvas safe={[top, right, bottom, left]}> the covered bands so targeted framings land in the clear part. Full-bleed lets a push-in fill the whole frame, which a boxed picture cannot.\n\n## Match cut through the subject (chapter seam)\nOne sentence: push in until the recurring object fills the frame, swap the world behind it, pull back to reveal the new world.\n- Use for: era/place/version changes where one object stays the subject (a button through four decades, a product through iterations). At most one signature seam style per piece; reuse it for every chapter seam.\n- Duration and energy: push 1.6\u20131.9 s, cover held about 1 s (the next action can happen under it), pull-back 2.4\u20132.8 s; high energy at the swap, calm after.\n- Set-up: put every version of the object with its centre on the same world point and add an invisible lens element there; give the versions one motion key so the new one morphs from the old size.\n- Beat 1 (end of chapter N): camera('lens', { pad: 0, zoom: 8\u20139, ms: 1800 }); start the next chapter's music here with fadeMs 2000\u20132600 (J-cut).\n- Beat 2 (first step of chapter N+1): switch the state that swaps the worlds (old interface exit=\"fade\", new interface enter=\"fade\", 800\u20131000 ms each) and in the same step camera('<new overview>', { ms: 2400\u20132800 }). The camera curve starts slowly, so the crossfade happens while the object still covers the frame, then the new world opens up. Put the chapter's timeline/scrubber movement and year label change in this same step.\n- Keep (do not downgrade): the shared centre point (otherwise the camera whips across the world at 8\u00D7 and the old ghost slides away), the slow-start pull-back, and exit/enter on whole interfaces rather than on each child.\n- Known pitfalls: a fine 1-px checker or hairline pattern behind the object shimmers (moir\u00E9) at high zoom \u2014 use a low-contrast texture; a deep link or timeline jump to beat 2 lands on the settled overview, which is what a viewer jumping chapters wants; verify the seam in the film strip (no red CUT) and at full size with --frames.\n- Reference: examples/button-40-years (works/forty.tsx, throughTheButton).\n\nAn older variant moves the object out of its interface into a central arrangement before the next chapter catches it (same motion key, exclusive when). It reads as a transfer beat rather than a cut; verify a mid-flight frame in playback because static sheets show only the declared endpoints.\n\n## A continuous object inside playable chapter interfaces\nUse one motion key for the recurring object and distinct element ids for its location in each mutually exclusive arrangement. Keep exactly one visible instance. Each interface should contain a real native input or declared local reaction: the same picture must make sense both during playback and after the viewer pauses.\n\nA useful story holds the message or task constant while the surrounding interface changes. The motion gives continuity; the input, menu and result prove the interaction paradigm. Label canned results explicitly when the audience can type arbitrary requests. Do not imply a model or backend computed a result.\n\nFor the match-cut transition above, use chapter() default continuation, and the engine's actionEntry: 'after' when a confirmed chapter drag should immediately show the new arrangement. Static storyboards prove layout; observe real playback to verify FLIP travel. If a flight does not appear, check for two visible same-key objects, a replaced Canvas/stage, or a manual jump with animate=false before changing the animation.\n\nKeep credits and sources outside the animated object area. Render every chapter and inspect the target frame after seeking; then test real typing, first-input pause, hover/touch, reset, continue and cross-chapter confirmation. A menu temporarily covering content is expected while open; verify it closes before the next action needs that content.\n\n## A news explainer as one map of clusters\nFor a topic explainer (an election, a policy, a market week), lay the whole episode out as one world of shot-sized clusters before writing steps.\n- Grid in narrative order: put clusters that hand over to each other side by side, so the adjacency is the camera route (ballot next to the seat chart, the map above the market it is called back to). A long diagonal move reads as a whip pan; use it once at most.\n- Reuse the same graphic across chapters instead of drawing a new board: a seat chart first lights up \"up for election\", then flips colour with the results, then gives up seats to a later chart. A map marks what is on the ballot, then the results, then is revisited for a later point (go back to one state).\n- Pin each opening question on the cluster that will answer it. When a chapter is on that cluster the tag says \"now\"; at the chapter end it turns into a short answer. Overview shots show a larger variant of the same tags (same motion key), so keep answers to about ten CJK characters and leave room for the large variant beside its cluster.\n- Make a number tangible by moving its marks: overlay the subset of marks that the number counts (for example the seats a party lost) with motion-keyed copies, light them up, then show the same keys arranged as a column in another cluster's chart while the camera moves there. The flight and the camera land together. Keep the original marks underneath so the source chart does not get holes, and size the dot grid so one dot equals one unit on the target chart's scale.\n- Results that pile up become the recap: a stamp lands large on the document it judges (enter=\"zoom\" with an enterDelay that waits for the document's flight), and on the next step the same motion key moves it into a row of small badges at the bottom. The chapter's summary step is a wide shot of that row, not a bullet card.\n- Keep one document object flying between two sides and change its text instead of fading documents in and out; a hidden object that reappears flies from its last location.\n- Chrome around the player's own overlays: the subtitle floats at the bottom centre and the step title pops at the top left, so put the chapter label at the top right with the source line under it, and give <Canvas safe> those bands. A closing call to action on the final overview goes at the top too, so it does not cover the answered question tags.\n- Cause near, effect far: when the control the viewer acts on (a ballot row) and the thing it changes (a map two clusters away) cannot share one readable frame, split the beat into the action step framed on the control and a system step that moves the camera to the result. Zooming out until both fit (below about 0.6\u00D7) makes both unreadable.\n- Count-in colour changes: when a chart recolours (seats flipping party), stagger each mark's transition-delay by its distance from the nearest end, so colour grows in from both sides like an election-night tally instead of switching at once.\n- Native controls inside a large world (Radio, Checkbox, Select) keep their own small font size; scale the control group with CSS zoom (about 1.3\u20131.5) rather than restyling its internals, and check the label size in the storyboard.\n- Source lines name only sources you actually have. For a rule, cite the rule itself (a constitutional article, a statute); never write \"see reports by X\" as a guess.\n\n## Remaking a deck-like piece as a film\nSymptoms in an existing piece: one board per chapter (label, big title, panels, footer), a title card opening each chapter, hard cuts between layers, an on-screen headline that repeats the caption and the narration, and opening questions that are never closed.\n- Keep the data module, sources and licensed assets; rebuild only the stage and the script. Create the remake as another work in works/<new-key>.tsx and mark the old work draft: true. Both remain accessible locally; only the ready work is published. Use build/share --work <key> to publish just one piece; selecting a draft is an error.\n- Before TSX, map each old board to a cluster of one world and each old title card to a camera move. Turn on-screen sentences into labels: the subtitle carries the sentence.\n- Then follow the review loop: storyboard every chapter, film-strip the chain until CUT and STILL are gone, and play it in the board. If playback stutters, measure before changing the piece (npx joplo skill demo).\n\n## Pitfalls that make a film feel like slides\n\n## Pitfalls that make a film feel like slides\n- Several steps under the same camera() go still once the drift reaches its end: the same target and drift do not restart it, and the film strip marks STILL. Let the camera follow the action (the side where the document lands, the panel that just opened, the end of the chart being discussed) or give the step a new drift.\n- camera({ zoom }) is a cap, not a forced zoom. Padding expands the target bounds before fitting: a target already as wide as the safe area will zoom OUT when pad > 0 (870px / (870px + 2 \u00D7 70px) \u2248 0.86). For a full-width portrait target use pad: 0; for smaller targets start with 12\u201318 design pixels and inspect the frame. There is no minimum zoom clamp; fitting a larger target may require zooming out. If a cluster's shape does not match the safe area, neighbouring clusters show at the edges. Shape the opening cluster to the frame for a clean thumbnail.\n- <br> is not an element; write line breaks as '\n' with whiteSpace: 'pre-line'.\n- Holds with a frozen camera: drift is on by default; do not turn it off for reading holds \u2014 a 1\u20138 % eased push is enough. If the film strip still marks STILL, the drift is too weak for that framing (flat UI shows little change); raise zoom or add x/y.\n- Every element using the same entrance: vary by meaning (section 3b) and stagger with enterDelay; let new things start before old ones finish leaving.\n- A whole interface replaced in one frame (when swap without exit/enter) is a hard cut. Give both sides a transition or cover the swap with the subject.\n- Whole-screen white/colour flashes over a still picture look like a stalled player; keep the picture moving under any fade.\n\nCommon pitfall: For visual explainers, read npx joplo skill content: keep a continuous visual story, storyboard every chapter, film-strip the chain, and verify playback before claiming it works";
|
|
1
|
+
export declare const skill = "# Joplo content production: content\n\nFor explainers, tutorials, science and news-explainer pieces that should feel like a good video, not a deck: the viewer watches a world change while a voice explains it.\nAuthor one standalone work in works/<key>.tsx with work(); put chapter() slices under scenarios and narrate() in their steps. Chapters continue in declaration order by default. Works have covers and enter the project home page; no feature, review cases or pick is needed. Full example: examples/llm-explainer.\n\nInstall @joplo-app/plugin-content at the Joplo version; import content and add it to config.plugins. Import { Canvas, Split, camera } from this package; keep work, chapter, patch, narrate and hold from @joplo-app/kit. Use theme: 'content:studio' for the bundled CSS. No plugin is implicitly enabled.\n\n## Minimal work\nIn a project with content enabled in config.plugins (and the starter's type: module / JSX tsconfig):\n```tsx\n// works/explainer.tsx\nimport { work, chapter, narrate } from '@joplo-app/kit';\nimport { Canvas } from '@joplo-app/plugin-content';\nexport default work({ title: 'A request in motion', summary: 'Follow one request',\n stage: <Canvas w={1280} h={800} />,\n scenarios: {\n arrival: chapter('A request arrives', { expected: 'Understand where it starts' })\n .system('Arrive', narrate('A request arrives.')),\n response: chapter('The worker responds').system('Respond', narrate('The worker replies.')),\n },\n});\n```\nThis is the authoring skeleton; add a visible subject and real changing state before reviewing the film. stage/layers needs no routes/ directory. Use on/routes explicitly when reusing product pages. WORK_INVALID means repair the required fields or slice builders; WORK_SLICES_MIXED means use chapter() consistently; FROM_UNKNOWN lists valid keys; WORK_EMPTY means add your first slice. Keep render/deep-link ids from outline --format json (standalone: explainer.arrival; feature-attached: queue.a.waiting), while --work takes the public entry key.\n\n## 1. Before TSX: package and plan within the agreed scope\n- One thing the viewer should be able to repeat afterwards, in one sentence.\n- Package first: the title asks the question; a thumbnail line of at most five words gives the surprising answer (complement the title, never repeat it); chapter('Slice title', { description }) is the cover sentence. The share preview is the first scenario's first frame, so design that frame as a thumbnail: one big line, one focal object, high contrast.\n- If the framing is unresolved, offer two or three devices (one running example, misconception then correction, a number made tangible, before and after) with a recommendation. Reuse an already agreed design; do not repeat approval rounds the user has waived.\n- Chapters: one question per chapter. Chapter titles are questions ('What does it actually read?'); the UI adds their numbers automatically. chapter('Slice title', { expected }) is what the viewer can now say. List every point from the source material and map each to a chapter or drop it on purpose.\n- One running example through every chapter (the same prompt, person, or data set), so each chapter builds on what the viewer already saw.\n- Write the script as one line per step: ears (narrate), eyes (what changes on stage), source. Adjacent steps should connect with 'but' or 'so'; a chain of 'and then' is flat.\n- Budget: narration reads about 4.5 CJK characters (2.5 English words) per second; 45\u201390 s per chapter. About 400 CJK characters can already exceed 90 seconds. npx joplo outline counts narration in its estimates.\n\n## Asset-first preparation\nBefore building a device, historical interface or illustrated object, make an asset list. Prefer a suitable licensed library, icon set or model; do not hand-write complex SVG or build a model merely because JSX can draw it. Verify the actual asset license, collect files in assets/, retain licenses and record author, URL and modifications in assets/SOURCES.md. Historical facts and historical appearance are separate evidence: label stylized reconstructions and invented messages, and avoid copied logos/system icons. Use original work only when a suitable reusable asset is unavailable, keeping it simple.\n\n## 2. Hook (first chapter, 20\u201335 s)\n- Beat 1: a familiar scene that pays off the thumbnail. Never a logo, an agenda, or a definition first.\n- Beat 2: the twist, shown on stage (the answer splits into pieces with probabilities, a name changes on the second try).\n- Beat 3: pull back and name the questions the episode answers. Pin each question where it will be answered, and close every loop later.\n\n## Camera sequences and persistent materials\nUse cameraSequence for a single long explanation that needs deliberate framing throughout (not high-frequency drawing). Import it from @joplo-app/plugin-content and put it in a scripted system step:\n```ts\ncameraSequence([\n { atMs: 0, target: 'room', zoom: 1 },\n { atMs: 2500, target: 'message', zoom: 1.15, ease: 'easeInOut' },\n { atMs: 6500, target: 'message', zoom: 1.22, ease: 'easeOut' },\n])\n```\nWaypoints start at 0, increase strictly, end within 60000 ms, and use existing element IDs (or targets: [...] for a group). Each waypoint may set pad/zoom; ease belongs to the incoming segment (easeInOut default, easeOut or linear). The step stays at least until the last waypoint. Pause and speed follow engine time. Static renders, deep-link jumps, animate=false and reduced motion show the final waypoint. Free exploration yields to the final layout. Existing camera() and drift remain valid; a sequence replaces drift for that framing state. An ordinary next step inherits the current path; explicitly issuing even the same cameraSequence again restarts it. A continuing chapter inherits the final frame until it issues a new sequence. End with camera() when changing the subject.\n\nFor the same subject changing material, keep one motion key and bind the destination layout, borderRadius, color, backgroundColor, opacity and text to state. Content interpolates those supported style values along the same motion flight; changed text crossfades through a temporary inert, aria-hidden clone without a second motion identity. Static jumps show destination styles immediately. This is a transition between authored states, not arbitrary per-frame drawing. Keep interactive controls in the live subject: the fading clone has no hit area or focus identity. Test long text at both endpoints and play the transition with Voice on; do not infer continuous motion from static storyboard frames.\n\n## 3. Not slides: one world, continuous objects, a moving camera (the core)\nFailure mode, even with nice graphics: one board per chapter (big title, panels, footer), chapter title cards, cards of bullets, things fading in and out. Viewers read it as a deck. Instead:\n- One layer holding one <Canvas w={2560} h={1600}> world (the default view is 1280\u00D7800, scaled to fit, never re-laid out; in a container without a height it sizes itself from the view ratio, and render warns 'Canvas has no size' if it still has none). Place a few containers absolutely in design pixels; lay out inside them with flex.\n- Objects keep their identity: give each one motion=\"key\". Write each arrangement as static JSX switched with when, reusing the same key; between steps Joplo flies the object from its old place and size to the new one, also across containers. Morph, never replace: the question's words split into tokens, flip into ids, then fly onto a tape; bars rearrange into a lottery strip.\n- When the same key also changes its look, the flight carries the change (see \"Camera sequences and persistent materials\"): the keyed element's own borderRadius, color, backgroundColor and opacity interpolate, and when its text, class, inline style or inner structure differ (a plain word becoming a coloured token, a 1984 button becoming a 1995 button, a label \"45%\" becoming \"98%\"), the old look crossfades out along the same flight. This also happens in place, when only the look changed. Write the two looks as two same-key elements switched with when, or bind the styles to state; jumps and screenshots show the new look.\n- shot() draws the host focus ring and caps UI zoom at 1.25\u00D7; use camera() for traveling inside a Canvas without that ring.\n- For diagram trace inside Canvas, pass { focus: false } to trace(...ids, options) so only the Canvas camera owns framing.\n- When another plugin effect also suggests host focus (for example a diagram trace inside a Canvas), use an explicit shot() for the whole director layer if the Canvas camera should own the framing. Otherwise host zoom and Canvas zoom can multiply and push nearby text out of view. Verify the actual visible bounds in playback, not only DOM text.\n- Camera: camera('id', \u2026) frames those elements (Joplo measures them, adds pad, caps zoom); camera() shows the whole canvas. Establish wide, push in on detail, pull back for the payoff. Object flights in the same step follow the camera's timing, so both land together.\n- Chapters continue: chapter() starts from the previous chapter's last frame (state, camera, director layer) by default. Only use from: null to restart, or from: 'sliceKey' for another predecessor; keep all slices chapter() within this work. patch($.ui, { \u2026 }) changes several values in one step.\n- System-only chapters stay on the initial director layer unless camera(), shot(), a cue, or chapter('Slice title', { layer }) selects another layer. Continuing from a chapter inherits its final layer; do not copy its state by hand.\n- screen children of the Canvas stay fixed on screen: chapter label, source line, poster, end card.\n- Takeaways land on objects (a pinned question flips to '\u2713 answer'); the recap is a pull back to the whole world. Use .card() only when nothing on stage can carry the moment.\n```tsx\n<Canvas w={2560} h={1600}>\n <div id=\"tape\" style={{ position: 'absolute', left: 120, top: 960, display: 'flex', gap: 8 }}>\n {IDS.map((t, i) => <span when={eq($.ui.at, 'tape')} motion={`tok_${i}`} style={{ background: COLORS[i] }}>{t}</span>)}\n </div>\n <div screen style={{ position: 'absolute', left: 20, top: 16 }}>{$.ui.chapter}</div>\n</Canvas>\nchapter('What does it read?')\n .system('Split', 'Nine characters, seven pieces', patch($.ui, { mode: 'split' }), camera('bubble', { pad: 160 }))\n .system('To the tape', 'It reads these numbers', patch($.ui, { at: 'tape' }), camera('tape', 'meter'))\n```\n- Anti-deck test: three or more steps that only show or hide whole panels, or a frame that is mostly text, means rebuild those steps as objects that move or change.\n\n## 3b. Transitions, drift and the safe area\n- enter / exit on any element inside the Canvas (world or screen layer): fade, rise, zoom, shrink, wipe, iris, grow, growUp, blur. Timing: enterMs / enterDelay / exitMs / exitDelay (0\u201310000 ms literals; defaults 600 / 450). Each preset is an \"away\" pose: enter goes away \u2192 the element's own look, exit goes own look \u2192 away. The grow left edge and growUp bottom edge stay anchored throughout entry and exit; they do not slide toward the default center as the size changes. Verify a middle frame as well as the final frame when aligning a growing bar with nearby content. So rise enters from below and exits sinking back; zoom lands from slightly larger and exits flying toward the camera; shrink grows from smaller and exits receding; wipe reveals left \u2192 right; iris opens from the centre; grow scales up from the left edge (horizontal bars, timeline rules, underlines) and growUp from the bottom edge (columns); blur comes into focus from a soft blur. The direction of grow / growUp is never guessed from the element's size: a short horizontal bar is narrower than it is tall and is still a horizontal bar. Set transform-origin in CSS to say where zoom/shrink grow from (a menu from its taskbar, a bubble from its tail).\n- enter plays when an element first appears (a new DOM node) during playback; exit plays when when becomes false: a non-interactive ghost copy keeps the last look and animates out, then disappears. Put enter + exit on two exclusive siblings in the same step for a crossfade. A same-motion-key element that flies (FLIP) never also enters or leaves.\n- How it settles: enterEase / exitEase / motionEase (FLIP flights) take smooth (default curve of each), snappy (fast start, short settle), spring (overshoots a little and settles), bounce (overshoots more, wobbles) or linear. The spring is a CSS linear() curve over the same ms, so it pauses, seeks and records like every other entrance; browsers without linear() get an overshooting cubic-bezier. Use spring for things that land or snap into place (a token joining a tape, a bar reaching its value, a call to action), bounce for one playful accent per chapter, snappy for typed or printed pieces; keep text the viewer is reading on smooth or snappy. motionEase overrides the camera-synchronised curve of a flight, so leave it unset when the camera moves in the same step.\n- Stagger a batch: enterStagger={ms} / exitStagger={ms} (0\u20132000) on a container delays the descendants that enter (or leave) in the same step by rank \u00D7 ms, in document order, on top of their own enterDelay. Only elements that actually play count: a same-key element that flies instead of entering does not take a slot, so \"three new tokens plus one that flies in\" staggers 0 / ms / 2\u00B7ms for the new three. Do not compute per-element enterDelay or animationDelay for a batch.\n- <Split text by=\"word\"|\"char\"> renders text that enters piece by piece: enter / enterMs / enterEase / enterDelay apply to every piece (default enter rise), the root does not enter itself, and enterStagger defaults to 70 ms (word) or 30 ms (char). Words come from Intl.Segmenter, so Chinese splits into words too; punctuation stays on its word (opening quotes and brackets on the next one) and lines never break inside a word. Screen readers read the whole sentence once. text may be a state binding: a new value is a new set of pieces and enters again (a chapter label in the screen layer). exit applies to the whole Split. Use it for a headline, a chapter label or an answer appearing; a body paragraph the viewer reads should not split.\n- Pick by meaning: fade for a whole-world swap under cover, rise for things that come from below (menus from a taskbar, keyboards, receipts), shrink for windows opening, zoom for something punching toward the viewer, wipe for typed/printed results, iris for a reveal from a point. Keep two or three per piece; do not give every element the same entrance.\n- camera(\u2026, { drift }) keeps the camera moving after it lands: a number = zoom factor reached over ms (default 8000), or { zoom, x, y, ms } with x/y in design px; false stops it. <Canvas drift={\u2026}> sets the default for every step; without either, a subtle 4 % / 8 s push applies. Drift eases in and out and stops at its end point; it freezes on pause, records in video, and screenshots/deep links show the settled frame without drift. The next camera move starts from where the drifting camera actually is, including when only drift changes or is switched off; the configured camera ms eases back to the target before the next drift.\n- <Canvas safe={[top, right, bottom, left]}> (design px) is the part of the view your screen-layer chrome covers. Targeted camera() frames fit inside the rest, and drift zooms around its centre; camera() with no ids still shows the whole world full-bleed.\n- UI life inside one interface (a caret blink, a stepped menu drop) can be CSS @keyframes in the project theme: the engine clock samples them, pause freezes them, static frames show their end state.\n\n## 4. Choose the information shape, then the picture\n- A number landing; before and after; ranking (bars from zero, length proportional); part of a whole (a strip whose segment widths are the shares); a process (one object going around a loop); misconception then fact; a timeline; a place (tiles or a simple map).\n- Similar sentences get different pictures. Labels sit on the thing they name; no legends when a direct label fits.\n- Compute numbers in TS from one source (for example probabilities from one set of scores) so every number on screen agrees. Label illustrative numbers on screen ('illustrative'), separate from sourced facts.\n\n## 5. Motion and layout numbers\n- Camera moves 1\u20131.5 s, ease in-out. Object flights 0.9 s ease-out; stagger 60\u2013120 ms (motionDelay); slow a landing pointer to 1.5\u20132 s (motionMs).\n- One primary motion per step; text that is being read does not move.\n- Entrances and exits: use enter / exit with enterEase and a container enterStagger (section 3b); a typed or word-by-word reveal is <Split> (by=\"char\", enter=\"blur\" or \"fade\", enterMs about 200, enterStagger 60\u2013160). Only for effects the presets do not cover put @keyframes and classes in themes/<name>.css and use className. Screenshots, thumbnails, and jumps show the end state. A 1 ms steps(1) CSS animation can stay stuck invisible in Chromium.\n- One accent color with a fixed meaning; color means the same thing in every chapter.\n- Size text for the frame you show: about 28 design px is the floor at 1\u00D7 zoom; a wide shot at 0.5\u00D7 needs 40 or more, or enlarge the labels for that shot (a bigger variant under the same motion key).\n- Frame by content (camera ids), not by guessed coordinates. Lay the world out as shot-sized clusters of roughly 16:10 (a machine with its output bars and strip, a chat with its bubbles); a cluster much wider than that leaves half the frame empty however you aim.\n- Same subject, same frame: keep one camera for consecutive steps about the same cluster; frame what stays on stage (not a container that has just emptied).\n\n## 6. Narration, captions, numbers\n- Caption: what the eye needs, ideally at most 16 CJK characters (24 is the hard limit). narrate(): what a presenter says, one or two sentences (rules: story section 6).\n- One number per step, rounded and written as spoken; translate numbers ('one chance in 365'). Pointing words are fine ('look at the dashed line').\n- When narration is on, keep on-stage text to labels; do not put the narrated sentence on screen too.\n\n## 7. Facts and sources\n- All facts in one data module with source and date; a source line (screen element) per chapter; name studies in narration ('OpenAI, in a 2025 paper, explains \u2026').\n- Say only what the source says. Bars start at zero. Separate illustrative values from facts on screen.\n- Images: licensed or public domain, credited, CREDITS file next to them (story section 7).\n\n## 8. Ending\n- Pull back to the whole world: every pinned question now shows its answer. Then one concrete action the viewer can take right away, as a screen element. Stop once the value lands; no 'thanks for watching'.\n\n## 9. Required: review before handing over\n- npx joplo check until 0 errors, then npx joplo outline --work <key>: verify the chapter order, step counts and estimated duration. Standalone works do not run feature coverage or HAPPY_PATH_ONLY checks.\n- Storyboard every chapter: npx joplo render --scenario-id <id> --sheet --out board.png prints every step in one image with its caption and narration. Read it frame by frame and assume the first one has problems: half-empty frames, objects cut at the edge, labels overlapping, text too small in wide shots, the chapter label covering content. Fix, then storyboard again.\n- Film-strip every chain of chapters: npx joplo render <dir> --scenario-id <first> --film --chain --out film.png. Fix every red CUT (one-frame full-screen change) unless it is your one deliberate cut, and every grey STILL (no visible change for \u2265 1.5 s). The storyboard cannot show either. Engine checklist: npx joplo skill demo, \"Make it play like a film\".\n- Play each chapter in the board with Voice on: flights and camera land together, nothing leaves the frame mid-flight, narration finishes before the next step.\n- Evidence, not belief: 'it plays' needs check 0 errors plus a run in the board; 'it looks right' needs the rendered frames; 'it is clear' needs captions-only and frames-only passes that both tell the story.\n- Tell the user what you could not verify (a real voice on a phone, other window sizes).\n\n## Migrating an existing script safely\n- Freeze the previous dev IR before moving files. Compare all steps, plugin drawing/media snapshots and every stateAt position after migration; a flow-to-chapter rename does not prove the same continuous state, motion or sound.\n- A chapter that previously began independently needs from: null. Default continuation carries the previous ui/data/inputs and running music; use it only when the next chapter should inherit that ending.\n- Put audience descriptions from feature.roles into audience. Preserve real role() speakers, the role keys used by say(), and config.voice.roles together; verify the chosen voices in playback.\n- If the project already has a helper named chapter, rename that helper before importing chapter from the kit.\n- Remove manual numbering from the chapter title itself, not every identical string. A transition card or caption may still use the old source text; let i18n missing/stale/unused diagnostics determine which translation keys need changing.\n- Inspect a path page before deleting it. A Slot-only/empty wrapper can be removed for stage/layers; reuse actual picture content through explicit on or the work's routes.\n- To prove a draft did not publish, search all build artifacts for one complete sentence unique to the old work and absent as a substring of current copy. Keep the old work locally with draft: true; do not rely on the published menu alone.\n\n## Diagnostics and recovery\n- CAMERA_UNKNOWN: the id must exist in a current layer or stage; frame elements inside this Canvas. CAMERA_INVALID: pad 0\u20132000, zoom 0.1\u201310, ms 0\u201310000, drift false | 0.5\u20132 | { zoom 0.5\u20132, x/y \u22122000\u20132000, ms 500\u201360000 }, finite numbers only; <Canvas drift> takes the same values and <Canvas safe> is four numbers 0\u20132000.\n- PLUGIN_PROPERTY_INVALID: motion is a nonempty string; motionDelay/motionMs/enterMs/enterDelay/exitMs/exitDelay are finite numbers 0\u201310000; enterStagger/exitStagger are 0\u20132000; screen is boolean; enter/exit are one of fade, rise, zoom, shrink, wipe, iris, grow, growUp, blur; enterEase/exitEase/motionEase are one of smooth, snappy, spring, bounce, linear.\n- SPLIT_INVALID: <Split> needs a nonempty text prop (a literal or a state binding), by is word or char, and the text goes in text, not in children. These universal properties are literals, not state bindings. Use separate same-key elements with when for a flight between containers.\n- Exit ghosts appear only during playback, never in screenshots, thumbnails, deep links, reduced motion or after a jump. They settle instantly (enter jumps to its end, ghosts vanish) on a jump, stop, scene change and the viewer's first input on the stage (a click, key or drag; the player's pause button keeps them frozen), so the input always acts on the final picture. The camera does not settle on input: it freezes where it is. Ghosts carry no id: camera, hints and Alt-click never target them.\n- Known limits (0.3.0): put exit on the removed container itself \u2014 an exit only on a child of a removed, transformed (scaled) container loses that ancestor's transform for its first frame. An element removed while its enter is still running exits from its base look (a small jump): keep enter shorter than the step. Two elements sharing a motion key with the same layout get neither enter nor exit: use different keys, or change the layout so a flight happens.\n- Give each visible object one motion key. Hidden previous locations remain available for a later same-key arrival. Avoid duplicate simultaneously visible keys. Independent translate/scale keeps the author's transform intact.\n- Cross-container flights temporarily lift clipping ancestors inside the world and restore their overflow at finish/cancel. During playground edits the flight yields its visual transform to the final usable layout while preserving its animation/time anchor for resume. Do not globally remove device clipping or duplicate the animated control to make it clickable; test first input during a flight.\n- Keep camera and FLIP duration together when both move; motionMs explicitly overrides duration, including 0. animate=false cancels an existing flight and renders the final layout.\n- A Canvas with no parent height uses its view aspect ratio; with an explicit parent height it fills that parent. A zero-sized parent still needs a layout fix; render reports the measured surface.\n- screen only separates direct Canvas children into the fixed overlay. Nested screen props remain ordinary descendants.\n- One world per continuous chapter; use chapter() default continuation to avoid manually copied end states. The initial frame and every step contain complete compiled drawing snapshots; deep links do not replay plugin logic.\n- HAPPY_PATH_ONLY belongs to feature review. If an explainer receives it, move the piece to works/<key>.tsx with work()/chapter() and remove its artificial cases; do not invent product failures. Review every storyboard and verify animation separately from static renders.\n";
|
|
2
|
+
export declare const patterns = "\n## Updating a public design replay from implementation evidence\nPreserve historical scenarios and stable feature/work IDs; append a clearly labeled source-derived update instead of rewriting an old approval. Put current status and limits in the visible scene: local implementation, work in progress, deployed and published are different claims. Commands displayed in a prototype are not real execution evidence. Reuse a new director layer when a work is already layered; for a route-only work, add a work-local route so adding the evidence view does not replace the original default stage. Keep the host badge/narration safe areas visible during verification.\n\n## Dual-aspect explainers with source metadata\nWhen adapting one dataset to landscape and portrait, author two arrangements at readable design sizes; do not shrink the landscape composition wholesale. For native export also set the logical stage with render --viewport WIDTHxHEIGHT --no-frame; output --width/--height alone only change the surrounding frame. Reserve separate areas for brand, main subject, image credit, source/fact status and subtitles. Also leave room for host chrome: the step badge at the top and current narration/completion bar at the bottom. Check with chrome visible, not only clean video. Give photo panels an explicit image height and adjustable object-position; credit and archive year need their own measured height below the image. A title-first opening may place one main graphic below the title.\n\nFor bilingual quotations show the full original, a translation explicitly labeled as translation, name, role, date and source. Test long original text and a long source name in both aspects; their actual wrapped heights determine the layout, not a short placeholder. Status labels and explanations belong to the author: preserve their meaning rather than replacing prediction, announcement or confirmation with one generic badge.\n\nUse a two-ended proportion bar when a dense point plot becomes unreadable in portrait. Keep left + right <= total and show total-left-right as undecided; position optional thresholds against the full total, not only the decided portion. Test the pure ratio calculation, then inspect real rendered chapters for text overflow. Shared wrapper components should forward bindings and when/enter/exit/motion props.\n\nSee examples/explainer-layouts: shared fictional data, local original vector illustration explicitly labeled non-photographic, short/long quote chapters and customizable status. These components are example-owned; the independent templates repository is maintained separately. No external facts, paid generation or online images are required.\n# content recipes and pitfalls\n\n## Museum-film composition\n- Collect licensed artwork and a real subject asset first. Let an archival image supply the historical texture and the subject supply the action; use CSS only for framing, gradients and typography. Label illustrative artwork when it is not evidence of the place or event.\n- Put the Canvas inside a wrapper with an explicit height (for a board-filling root, height:100%). An auto-height wrapper can remain 800px tall while the board is shorter: exports look correct but lower controls are clipped. Test the actual board at a short height as well as render.\n- Keep chapter/source labels as direct screen children when the world camera travels. Nested screen does not escape its parent. Frame a stable hero cluster with a modest pad; an oversized pad may zoom out and expose empty margins instead of producing a close-up.\n- For a subject entering a device, establish the device first or in the same step, then shrink and move the subject into its screen. Keep the ending actionable through real forks or controls. Reuse the stable subject identity described below.\n- Match-cut the subject at a chapter boundary while changing its background and sound in that same scripted step. The input stays concrete: click the object, drag it to a visible destination, or choose an explicitly labeled branch. Avoid a slide of historical bullet points.\n\n## Shot grammar for a playable short film\nGive each chapter a visual arc: establish the whole interface/device, move in on the meaningful input or action, show its result, then pull back. Keep chapter numbers and explanations subordinate to the working surface. Judge text at its final painted size, including Canvas scale and camera zoom, rather than the font-size declaration alone.\n\nUse camera ids for the object that matters. Framing a wide window rarely produces a button close-up; frame the button for anticipation and button plus receipt for the result. Keep those targets inside one visual cluster. A deliberate crop is useful; a required action cropped out of the current frame is a broken shot.\n\nWhen a whole-stage camera would collide with navigation or titles, either put Canvas in a separately sized parent whose view matches the picture region (controls stay in the surrounding layout), or go full-bleed: put the title and timeline on the screen layer over the moving picture and give <Canvas safe={[top, right, bottom, left]}> the covered bands so targeted framings land in the clear part. Full-bleed lets a push-in fill the whole frame, which a boxed picture cannot.\n\n## Match cut through the subject (chapter seam)\nOne sentence: push in until the recurring object fills the frame, swap the world behind it, pull back to reveal the new world.\n- Use for: era/place/version changes where one object stays the subject (a button through four decades, a product through iterations). At most one signature seam style per piece; reuse it for every chapter seam.\n- Duration and energy: push 1.6\u20131.9 s, cover held about 1 s (the next action can happen under it), pull-back 2.4\u20132.8 s; high energy at the swap, calm after.\n- Set-up: put every version of the object with its centre on the same world point and add an invisible lens element there; give the versions one motion key so the new one morphs from the old size.\n- Beat 1 (end of chapter N): camera('lens', { pad: 0, zoom: 8\u20139, ms: 1800 }); start the next chapter's music here with fadeMs 2000\u20132600 (J-cut).\n- Beat 2 (first step of chapter N+1): switch the state that swaps the worlds (old interface exit=\"fade\", new interface enter=\"fade\", 800\u20131000 ms each) and in the same step camera('<new overview>', { ms: 2400\u20132800 }). The camera curve starts slowly, so the crossfade happens while the object still covers the frame, then the new world opens up. Put the chapter's timeline/scrubber movement and year label change in this same step.\n- Keep (do not downgrade): the shared centre point (otherwise the camera whips across the world at 8\u00D7 and the old ghost slides away), the slow-start pull-back, and exit/enter on whole interfaces rather than on each child.\n- Known pitfalls: a fine 1-px checker or hairline pattern behind the object shimmers (moir\u00E9) at high zoom \u2014 use a low-contrast texture; a deep link or timeline jump to beat 2 lands on the settled overview, which is what a viewer jumping chapters wants; verify the seam in the film strip (no red CUT) and at full size with --frames.\n- Reference: examples/button-40-years (works/forty.tsx, throughTheButton).\n\nAn older variant moves the object out of its interface into a central arrangement before the next chapter catches it (same motion key, exclusive when). It reads as a transfer beat rather than a cut; verify a mid-flight frame in playback because static sheets show only the declared endpoints.\n\n## A continuous object inside playable chapter interfaces\nUse one motion key for the recurring object and distinct element ids for its location in each mutually exclusive arrangement. Keep exactly one visible instance. Each interface should contain a real native input or declared local reaction: the same picture must make sense both during playback and after the viewer pauses.\n\nA useful story holds the message or task constant while the surrounding interface changes. The motion gives continuity; the input, menu and result prove the interaction paradigm. Label canned results explicitly when the audience can type arbitrary requests. Do not imply a model or backend computed a result.\n\nFor the match-cut transition above, use chapter() default continuation, and the engine's actionEntry: 'after' when a confirmed chapter drag should immediately show the new arrangement. Static storyboards prove layout; observe real playback to verify FLIP travel. If a flight does not appear, check for two visible same-key objects, a replaced Canvas/stage, or a manual jump with animate=false before changing the animation.\n\nKeep credits and sources outside the animated object area. Render every chapter and inspect the target frame after seeking; then test real typing, first-input pause, hover/touch, reset, continue and cross-chapter confirmation. A menu temporarily covering content is expected while open; verify it closes before the next action needs that content.\n\n## A news explainer as one map of clusters\nFor a topic explainer (an election, a policy, a market week), lay the whole episode out as one world of shot-sized clusters before writing steps.\n- Grid in narrative order: put clusters that hand over to each other side by side, so the adjacency is the camera route (ballot next to the seat chart, the map above the market it is called back to). A long diagonal move reads as a whip pan; use it once at most.\n- Reuse the same graphic across chapters instead of drawing a new board: a seat chart first lights up \"up for election\", then flips colour with the results, then gives up seats to a later chart. A map marks what is on the ballot, then the results, then is revisited for a later point (go back to one state).\n- Pin each opening question on the cluster that will answer it. When a chapter is on that cluster the tag says \"now\"; at the chapter end it turns into a short answer. Overview shots show a larger variant of the same tags (same motion key), so keep answers to about ten CJK characters and leave room for the large variant beside its cluster.\n- Make a number tangible by moving its marks: overlay the subset of marks that the number counts (for example the seats a party lost) with motion-keyed copies, light them up, then show the same keys arranged as a column in another cluster's chart while the camera moves there. The flight and the camera land together. Keep the original marks underneath so the source chart does not get holes, and size the dot grid so one dot equals one unit on the target chart's scale.\n- Results that pile up become the recap: a stamp lands large on the document it judges (enter=\"zoom\" with an enterDelay that waits for the document's flight), and on the next step the same motion key moves it into a row of small badges at the bottom. The chapter's summary step is a wide shot of that row, not a bullet card.\n- Keep one document object flying between two sides and change its text instead of fading documents in and out; a hidden object that reappears flies from its last location.\n- Chrome around the player's own overlays: the subtitle floats at the bottom centre and the step title pops at the top left, so put the chapter label at the top right with the source line under it, and give <Canvas safe> those bands. A closing call to action on the final overview goes at the top too, so it does not cover the answered question tags.\n- Cause near, effect far: when the control the viewer acts on (a ballot row) and the thing it changes (a map two clusters away) cannot share one readable frame, split the beat into the action step framed on the control and a system step that moves the camera to the result. Zooming out until both fit (below about 0.6\u00D7) makes both unreadable.\n- Count-in colour changes: when a chart recolours (seats flipping party), stagger each mark's transition-delay by its distance from the nearest end, so colour grows in from both sides like an election-night tally instead of switching at once.\n- Native controls inside a large world (Radio, Checkbox, Select) keep their own small font size; scale the control group with CSS zoom (about 1.3\u20131.5) rather than restyling its internals, and check the label size in the storyboard.\n- Source lines name only sources you actually have. For a rule, cite the rule itself (a constitutional article, a statute); never write \"see reports by X\" as a guess.\n\n## Remaking a deck-like piece as a film\nSymptoms in an existing piece: one board per chapter (label, big title, panels, footer), a title card opening each chapter, hard cuts between layers, an on-screen headline that repeats the caption and the narration, and opening questions that are never closed.\n- Keep the data module, sources and licensed assets; rebuild only the stage and the script. Create the remake as another work in works/<new-key>.tsx and mark the old work draft: true. Both remain accessible locally; only the ready work is published. Use build/share --work <key> to publish just one piece; selecting a draft is an error.\n- Before TSX, map each old board to a cluster of one world and each old title card to a camera move. Turn on-screen sentences into labels: the subtitle carries the sentence.\n- Then follow the review loop: storyboard every chapter, film-strip the chain until CUT and STILL are gone, and play it in the board. If playback stutters, measure before changing the piece (npx joplo skill demo).\n\n## Pitfalls that make a film feel like slides\n\n## Pitfalls that make a film feel like slides\n- Several steps under the same camera() go still once the drift reaches its end: the same target and drift do not restart it, and the film strip marks STILL. Let the camera follow the action (the side where the document lands, the panel that just opened, the end of the chart being discussed) or give the step a new drift.\n- camera({ zoom }) is a cap, not a forced zoom. Padding expands the target bounds before fitting: a target already as wide as the safe area will zoom OUT when pad > 0 (870px / (870px + 2 \u00D7 70px) \u2248 0.86). For a full-width portrait target use pad: 0; for smaller targets start with 12\u201318 design pixels and inspect the frame. There is no minimum zoom clamp; fitting a larger target may require zooming out. If a cluster's shape does not match the safe area, neighbouring clusters show at the edges. Shape the opening cluster to the frame for a clean thumbnail.\n- <br> is not an element; write line breaks as '\n' with whiteSpace: 'pre-line'.\n- Holds with a frozen camera: drift is on by default; do not turn it off for reading holds \u2014 a 1\u20138 % eased push is enough. If the film strip still marks STILL, the drift is too weak for that framing (flat UI shows little change); raise zoom or add x/y.\n- Every element using the same entrance: vary by meaning (section 3b) and stagger a batch with enterStagger on its container; let new things start before old ones finish leaving.\n- Everything springs: a spring on every entrance reads as a toy. Springs for things that land, smooth or snappy for text and frames, bounce at most once a chapter.\n- Put the look you want to interpolate on the element that carries the motion key. Changes inside it (an inner wrapper's background, a bevelled border, a gradient) only crossfade; border colours, shadows and background images do not interpolate.\n- Put enter (and enterEase) on the element that carries the motion key, not on a wrapper around it: when the key flies in from elsewhere the wrapper would still enter and the piece would both fly and fade.\n- A whole interface replaced in one frame (when swap without exit/enter) is a hard cut. Give both sides a transition or cover the swap with the subject.\n- Whole-screen white/colour flashes over a still picture look like a stalled player; keep the picture moving under any fade.\n\nFor runtime layout QA, use joplo render --audit-layout for a final-state screenshot and --film --audit-layout for motion. Declare important selectors, a content frame and reserved footer/subtitle rectangles; exclude intentional stamps/background overlays. Text Range bounds reflect loaded fonts and actual Canvas scaling. Canvas exposes its existing engine-clock camera, drift midpoint/end and sequence-waypoint deadlines only as DOM diagnostic hints; static/jump/exploration states do not claim future motion. A later step can interrupt a phase, and masks/rotation or hidden content remain unknown rather than \"visible\". Inspect evidence before changing intentional overlap.\n\nCommon pitfall: For visual explainers, read npx joplo skill content: keep a continuous visual story, storyboard every chapter, film-strip the chain, and verify playback before claiming it works";
|
package/dist/guide.js
CHANGED
|
@@ -3,7 +3,7 @@ export const skill = `# Joplo content production: content
|
|
|
3
3
|
For explainers, tutorials, science and news-explainer pieces that should feel like a good video, not a deck: the viewer watches a world change while a voice explains it.
|
|
4
4
|
Author one standalone work in works/<key>.tsx with work(); put chapter() slices under scenarios and narrate() in their steps. Chapters continue in declaration order by default. Works have covers and enter the project home page; no feature, review cases or pick is needed. Full example: examples/llm-explainer.
|
|
5
5
|
|
|
6
|
-
Install @joplo-app/plugin-content at the Joplo version; import content and add it to config.plugins. Import { Canvas, camera } from this package; keep work, chapter, patch, narrate and hold from @joplo-app/kit. Use theme: 'content:studio' for the bundled CSS. No plugin is implicitly enabled.
|
|
6
|
+
Install @joplo-app/plugin-content at the Joplo version; import content and add it to config.plugins. Import { Canvas, Split, camera } from this package; keep work, chapter, patch, narrate and hold from @joplo-app/kit. Use theme: 'content:studio' for the bundled CSS. No plugin is implicitly enabled.
|
|
7
7
|
|
|
8
8
|
## Minimal work
|
|
9
9
|
In a project with content enabled in config.plugins (and the starter's type: module / JSX tsconfig):
|
|
@@ -39,11 +39,26 @@ Before building a device, historical interface or illustrated object, make an as
|
|
|
39
39
|
- Beat 2: the twist, shown on stage (the answer splits into pieces with probabilities, a name changes on the second try).
|
|
40
40
|
- Beat 3: pull back and name the questions the episode answers. Pin each question where it will be answered, and close every loop later.
|
|
41
41
|
|
|
42
|
+
## Camera sequences and persistent materials
|
|
43
|
+
Use cameraSequence for a single long explanation that needs deliberate framing throughout (not high-frequency drawing). Import it from @joplo-app/plugin-content and put it in a scripted system step:
|
|
44
|
+
\`\`\`ts
|
|
45
|
+
cameraSequence([
|
|
46
|
+
{ atMs: 0, target: 'room', zoom: 1 },
|
|
47
|
+
{ atMs: 2500, target: 'message', zoom: 1.15, ease: 'easeInOut' },
|
|
48
|
+
{ atMs: 6500, target: 'message', zoom: 1.22, ease: 'easeOut' },
|
|
49
|
+
])
|
|
50
|
+
\`\`\`
|
|
51
|
+
Waypoints start at 0, increase strictly, end within 60000 ms, and use existing element IDs (or targets: [...] for a group). Each waypoint may set pad/zoom; ease belongs to the incoming segment (easeInOut default, easeOut or linear). The step stays at least until the last waypoint. Pause and speed follow engine time. Static renders, deep-link jumps, animate=false and reduced motion show the final waypoint. Free exploration yields to the final layout. Existing camera() and drift remain valid; a sequence replaces drift for that framing state. An ordinary next step inherits the current path; explicitly issuing even the same cameraSequence again restarts it. A continuing chapter inherits the final frame until it issues a new sequence. End with camera() when changing the subject.
|
|
52
|
+
|
|
53
|
+
For the same subject changing material, keep one motion key and bind the destination layout, borderRadius, color, backgroundColor, opacity and text to state. Content interpolates those supported style values along the same motion flight; changed text crossfades through a temporary inert, aria-hidden clone without a second motion identity. Static jumps show destination styles immediately. This is a transition between authored states, not arbitrary per-frame drawing. Keep interactive controls in the live subject: the fading clone has no hit area or focus identity. Test long text at both endpoints and play the transition with Voice on; do not infer continuous motion from static storyboard frames.
|
|
54
|
+
|
|
42
55
|
## 3. Not slides: one world, continuous objects, a moving camera (the core)
|
|
43
56
|
Failure mode, even with nice graphics: one board per chapter (big title, panels, footer), chapter title cards, cards of bullets, things fading in and out. Viewers read it as a deck. Instead:
|
|
44
57
|
- One layer holding one <Canvas w={2560} h={1600}> world (the default view is 1280×800, scaled to fit, never re-laid out; in a container without a height it sizes itself from the view ratio, and render warns 'Canvas has no size' if it still has none). Place a few containers absolutely in design pixels; lay out inside them with flex.
|
|
45
58
|
- Objects keep their identity: give each one motion="key". Write each arrangement as static JSX switched with when, reusing the same key; between steps Joplo flies the object from its old place and size to the new one, also across containers. Morph, never replace: the question's words split into tokens, flip into ids, then fly onto a tape; bars rearrange into a lottery strip.
|
|
59
|
+
- When the same key also changes its look, the flight carries the change (see "Camera sequences and persistent materials"): the keyed element's own borderRadius, color, backgroundColor and opacity interpolate, and when its text, class, inline style or inner structure differ (a plain word becoming a coloured token, a 1984 button becoming a 1995 button, a label "45%" becoming "98%"), the old look crossfades out along the same flight. This also happens in place, when only the look changed. Write the two looks as two same-key elements switched with when, or bind the styles to state; jumps and screenshots show the new look.
|
|
46
60
|
- shot() draws the host focus ring and caps UI zoom at 1.25×; use camera() for traveling inside a Canvas without that ring.
|
|
61
|
+
- For diagram trace inside Canvas, pass { focus: false } to trace(...ids, options) so only the Canvas camera owns framing.
|
|
47
62
|
- When another plugin effect also suggests host focus (for example a diagram trace inside a Canvas), use an explicit shot() for the whole director layer if the Canvas camera should own the framing. Otherwise host zoom and Canvas zoom can multiply and push nearby text out of view. Verify the actual visible bounds in playback, not only DOM text.
|
|
48
63
|
- Camera: camera('id', …) frames those elements (Joplo measures them, adds pad, caps zoom); camera() shows the whole canvas. Establish wide, push in on detail, pull back for the payoff. Object flights in the same step follow the camera's timing, so both land together.
|
|
49
64
|
- Chapters continue: chapter() starts from the previous chapter's last frame (state, camera, director layer) by default. Only use from: null to restart, or from: 'sliceKey' for another predecessor; keep all slices chapter() within this work. patch($.ui, { … }) changes several values in one step.
|
|
@@ -64,8 +79,11 @@ chapter('What does it read?')
|
|
|
64
79
|
- Anti-deck test: three or more steps that only show or hide whole panels, or a frame that is mostly text, means rebuild those steps as objects that move or change.
|
|
65
80
|
|
|
66
81
|
## 3b. Transitions, drift and the safe area
|
|
67
|
-
- enter / exit on any element inside the Canvas (world or screen layer): fade, rise, zoom, shrink, wipe, iris. Timing: enterMs / enterDelay / exitMs / exitDelay (0–10000 ms literals; defaults 600 / 450). Each preset is an "away" pose: enter goes away → the element's own look, exit goes own look → away. So rise enters from below and exits sinking back; zoom lands from slightly larger and exits flying toward the camera; shrink grows from smaller and exits receding; wipe reveals left → right; iris opens from the centre. Set transform-origin in CSS to say where zoom/shrink grow from (a menu from its taskbar, a bubble from its tail).
|
|
82
|
+
- enter / exit on any element inside the Canvas (world or screen layer): fade, rise, zoom, shrink, wipe, iris, grow, growUp, blur. Timing: enterMs / enterDelay / exitMs / exitDelay (0–10000 ms literals; defaults 600 / 450). Each preset is an "away" pose: enter goes away → the element's own look, exit goes own look → away. The grow left edge and growUp bottom edge stay anchored throughout entry and exit; they do not slide toward the default center as the size changes. Verify a middle frame as well as the final frame when aligning a growing bar with nearby content. So rise enters from below and exits sinking back; zoom lands from slightly larger and exits flying toward the camera; shrink grows from smaller and exits receding; wipe reveals left → right; iris opens from the centre; grow scales up from the left edge (horizontal bars, timeline rules, underlines) and growUp from the bottom edge (columns); blur comes into focus from a soft blur. The direction of grow / growUp is never guessed from the element's size: a short horizontal bar is narrower than it is tall and is still a horizontal bar. Set transform-origin in CSS to say where zoom/shrink grow from (a menu from its taskbar, a bubble from its tail).
|
|
68
83
|
- enter plays when an element first appears (a new DOM node) during playback; exit plays when when becomes false: a non-interactive ghost copy keeps the last look and animates out, then disappears. Put enter + exit on two exclusive siblings in the same step for a crossfade. A same-motion-key element that flies (FLIP) never also enters or leaves.
|
|
84
|
+
- How it settles: enterEase / exitEase / motionEase (FLIP flights) take smooth (default curve of each), snappy (fast start, short settle), spring (overshoots a little and settles), bounce (overshoots more, wobbles) or linear. The spring is a CSS linear() curve over the same ms, so it pauses, seeks and records like every other entrance; browsers without linear() get an overshooting cubic-bezier. Use spring for things that land or snap into place (a token joining a tape, a bar reaching its value, a call to action), bounce for one playful accent per chapter, snappy for typed or printed pieces; keep text the viewer is reading on smooth or snappy. motionEase overrides the camera-synchronised curve of a flight, so leave it unset when the camera moves in the same step.
|
|
85
|
+
- Stagger a batch: enterStagger={ms} / exitStagger={ms} (0–2000) on a container delays the descendants that enter (or leave) in the same step by rank × ms, in document order, on top of their own enterDelay. Only elements that actually play count: a same-key element that flies instead of entering does not take a slot, so "three new tokens plus one that flies in" staggers 0 / ms / 2·ms for the new three. Do not compute per-element enterDelay or animationDelay for a batch.
|
|
86
|
+
- <Split text by="word"|"char"> renders text that enters piece by piece: enter / enterMs / enterEase / enterDelay apply to every piece (default enter rise), the root does not enter itself, and enterStagger defaults to 70 ms (word) or 30 ms (char). Words come from Intl.Segmenter, so Chinese splits into words too; punctuation stays on its word (opening quotes and brackets on the next one) and lines never break inside a word. Screen readers read the whole sentence once. text may be a state binding: a new value is a new set of pieces and enters again (a chapter label in the screen layer). exit applies to the whole Split. Use it for a headline, a chapter label or an answer appearing; a body paragraph the viewer reads should not split.
|
|
69
87
|
- Pick by meaning: fade for a whole-world swap under cover, rise for things that come from below (menus from a taskbar, keyboards, receipts), shrink for windows opening, zoom for something punching toward the viewer, wipe for typed/printed results, iris for a reveal from a point. Keep two or three per piece; do not give every element the same entrance.
|
|
70
88
|
- camera(…, { drift }) keeps the camera moving after it lands: a number = zoom factor reached over ms (default 8000), or { zoom, x, y, ms } with x/y in design px; false stops it. <Canvas drift={…}> sets the default for every step; without either, a subtle 4 % / 8 s push applies. Drift eases in and out and stops at its end point; it freezes on pause, records in video, and screenshots/deep links show the settled frame without drift. The next camera move starts from where the drifting camera actually is, including when only drift changes or is switched off; the configured camera ms eases back to the target before the next drift.
|
|
71
89
|
- <Canvas safe={[top, right, bottom, left]}> (design px) is the part of the view your screen-layer chrome covers. Targeted camera() frames fit inside the rest, and drift zooms around its centre; camera() with no ids still shows the whole world full-bleed.
|
|
@@ -79,7 +97,7 @@ chapter('What does it read?')
|
|
|
79
97
|
## 5. Motion and layout numbers
|
|
80
98
|
- Camera moves 1–1.5 s, ease in-out. Object flights 0.9 s ease-out; stagger 60–120 ms (motionDelay); slow a landing pointer to 1.5–2 s (motionMs).
|
|
81
99
|
- One primary motion per step; text that is being read does not move.
|
|
82
|
-
- Entrances and exits: use enter / exit (section 3b); for effects the presets do not cover put @keyframes and classes in themes/<name>.css and use className
|
|
100
|
+
- Entrances and exits: use enter / exit with enterEase and a container enterStagger (section 3b); a typed or word-by-word reveal is <Split> (by="char", enter="blur" or "fade", enterMs about 200, enterStagger 60–160). Only for effects the presets do not cover put @keyframes and classes in themes/<name>.css and use className. Screenshots, thumbnails, and jumps show the end state. A 1 ms steps(1) CSS animation can stay stuck invisible in Chromium.
|
|
83
101
|
- One accent color with a fixed meaning; color means the same thing in every chapter.
|
|
84
102
|
- Size text for the frame you show: about 28 design px is the floor at 1× zoom; a wide shot at 0.5× needs 40 or more, or enlarge the labels for that shot (a bigger variant under the same motion key).
|
|
85
103
|
- Frame by content (camera ids), not by guessed coordinates. Lay the world out as shot-sized clusters of roughly 16:10 (a machine with its output bars and strip, a chat with its bubbles); a cluster much wider than that leaves half the frame empty however you aim.
|
|
@@ -117,7 +135,8 @@ chapter('What does it read?')
|
|
|
117
135
|
|
|
118
136
|
## Diagnostics and recovery
|
|
119
137
|
- CAMERA_UNKNOWN: the id must exist in a current layer or stage; frame elements inside this Canvas. CAMERA_INVALID: pad 0–2000, zoom 0.1–10, ms 0–10000, drift false | 0.5–2 | { zoom 0.5–2, x/y −2000–2000, ms 500–60000 }, finite numbers only; <Canvas drift> takes the same values and <Canvas safe> is four numbers 0–2000.
|
|
120
|
-
- PLUGIN_PROPERTY_INVALID: motion is a nonempty string; motionDelay/motionMs/enterMs/enterDelay/exitMs/exitDelay are finite numbers 0–10000; screen is boolean; enter/exit are one of fade, rise, zoom, shrink, wipe, iris
|
|
138
|
+
- PLUGIN_PROPERTY_INVALID: motion is a nonempty string; motionDelay/motionMs/enterMs/enterDelay/exitMs/exitDelay are finite numbers 0–10000; enterStagger/exitStagger are 0–2000; screen is boolean; enter/exit are one of fade, rise, zoom, shrink, wipe, iris, grow, growUp, blur; enterEase/exitEase/motionEase are one of smooth, snappy, spring, bounce, linear.
|
|
139
|
+
- SPLIT_INVALID: <Split> needs a nonempty text prop (a literal or a state binding), by is word or char, and the text goes in text, not in children. These universal properties are literals, not state bindings. Use separate same-key elements with when for a flight between containers.
|
|
121
140
|
- Exit ghosts appear only during playback, never in screenshots, thumbnails, deep links, reduced motion or after a jump. They settle instantly (enter jumps to its end, ghosts vanish) on a jump, stop, scene change and the viewer's first input on the stage (a click, key or drag; the player's pause button keeps them frozen), so the input always acts on the final picture. The camera does not settle on input: it freezes where it is. Ghosts carry no id: camera, hints and Alt-click never target them.
|
|
122
141
|
- Known limits (0.3.0): put exit on the removed container itself — an exit only on a child of a removed, transformed (scaled) container loses that ancestor's transform for its first frame. An element removed while its enter is still running exits from its base look (a small jump): keep enter shorter than the step. Two elements sharing a motion key with the same layout get neither enter nor exit: use different keys, or change the layout so a flight happens.
|
|
123
142
|
- Give each visible object one motion key. Hidden previous locations remain available for a later same-key arrival. Avoid duplicate simultaneously visible keys. Independent translate/scale keeps the author's transform intact.
|
|
@@ -128,7 +147,19 @@ chapter('What does it read?')
|
|
|
128
147
|
- One world per continuous chapter; use chapter() default continuation to avoid manually copied end states. The initial frame and every step contain complete compiled drawing snapshots; deep links do not replay plugin logic.
|
|
129
148
|
- HAPPY_PATH_ONLY belongs to feature review. If an explainer receives it, move the piece to works/<key>.tsx with work()/chapter() and remove its artificial cases; do not invent product failures. Review every storyboard and verify animation separately from static renders.
|
|
130
149
|
`;
|
|
131
|
-
export const patterns =
|
|
150
|
+
export const patterns = `
|
|
151
|
+
## Updating a public design replay from implementation evidence
|
|
152
|
+
Preserve historical scenarios and stable feature/work IDs; append a clearly labeled source-derived update instead of rewriting an old approval. Put current status and limits in the visible scene: local implementation, work in progress, deployed and published are different claims. Commands displayed in a prototype are not real execution evidence. Reuse a new director layer when a work is already layered; for a route-only work, add a work-local route so adding the evidence view does not replace the original default stage. Keep the host badge/narration safe areas visible during verification.
|
|
153
|
+
|
|
154
|
+
## Dual-aspect explainers with source metadata
|
|
155
|
+
When adapting one dataset to landscape and portrait, author two arrangements at readable design sizes; do not shrink the landscape composition wholesale. For native export also set the logical stage with render --viewport WIDTHxHEIGHT --no-frame; output --width/--height alone only change the surrounding frame. Reserve separate areas for brand, main subject, image credit, source/fact status and subtitles. Also leave room for host chrome: the step badge at the top and current narration/completion bar at the bottom. Check with chrome visible, not only clean video. Give photo panels an explicit image height and adjustable object-position; credit and archive year need their own measured height below the image. A title-first opening may place one main graphic below the title.
|
|
156
|
+
|
|
157
|
+
For bilingual quotations show the full original, a translation explicitly labeled as translation, name, role, date and source. Test long original text and a long source name in both aspects; their actual wrapped heights determine the layout, not a short placeholder. Status labels and explanations belong to the author: preserve their meaning rather than replacing prediction, announcement or confirmation with one generic badge.
|
|
158
|
+
|
|
159
|
+
Use a two-ended proportion bar when a dense point plot becomes unreadable in portrait. Keep left + right <= total and show total-left-right as undecided; position optional thresholds against the full total, not only the decided portion. Test the pure ratio calculation, then inspect real rendered chapters for text overflow. Shared wrapper components should forward bindings and when/enter/exit/motion props.
|
|
160
|
+
|
|
161
|
+
See examples/explainer-layouts: shared fictional data, local original vector illustration explicitly labeled non-photographic, short/long quote chapters and customizable status. These components are example-owned; the independent templates repository is maintained separately. No external facts, paid generation or online images are required.
|
|
162
|
+
# content recipes and pitfalls
|
|
132
163
|
|
|
133
164
|
## Museum-film composition
|
|
134
165
|
- Collect licensed artwork and a real subject asset first. Let an archival image supply the historical texture and the subject supply the action; use CSS only for framing, gradients and typography. Label illustrative artwork when it is not evidence of the place or event.
|
|
@@ -193,8 +224,13 @@ Symptoms in an existing piece: one board per chapter (label, big title, panels,
|
|
|
193
224
|
- camera({ zoom }) is a cap, not a forced zoom. Padding expands the target bounds before fitting: a target already as wide as the safe area will zoom OUT when pad > 0 (870px / (870px + 2 × 70px) ≈ 0.86). For a full-width portrait target use pad: 0; for smaller targets start with 12–18 design pixels and inspect the frame. There is no minimum zoom clamp; fitting a larger target may require zooming out. If a cluster's shape does not match the safe area, neighbouring clusters show at the edges. Shape the opening cluster to the frame for a clean thumbnail.
|
|
194
225
|
- <br> is not an element; write line breaks as '\n' with whiteSpace: 'pre-line'.
|
|
195
226
|
- Holds with a frozen camera: drift is on by default; do not turn it off for reading holds — a 1–8 % eased push is enough. If the film strip still marks STILL, the drift is too weak for that framing (flat UI shows little change); raise zoom or add x/y.
|
|
196
|
-
- Every element using the same entrance: vary by meaning (section 3b) and stagger with
|
|
227
|
+
- Every element using the same entrance: vary by meaning (section 3b) and stagger a batch with enterStagger on its container; let new things start before old ones finish leaving.
|
|
228
|
+
- Everything springs: a spring on every entrance reads as a toy. Springs for things that land, smooth or snappy for text and frames, bounce at most once a chapter.
|
|
229
|
+
- Put the look you want to interpolate on the element that carries the motion key. Changes inside it (an inner wrapper's background, a bevelled border, a gradient) only crossfade; border colours, shadows and background images do not interpolate.
|
|
230
|
+
- Put enter (and enterEase) on the element that carries the motion key, not on a wrapper around it: when the key flies in from elsewhere the wrapper would still enter and the piece would both fly and fade.
|
|
197
231
|
- A whole interface replaced in one frame (when swap without exit/enter) is a hard cut. Give both sides a transition or cover the swap with the subject.
|
|
198
232
|
- Whole-screen white/colour flashes over a still picture look like a stalled player; keep the picture moving under any fade.
|
|
199
233
|
|
|
234
|
+
For runtime layout QA, use joplo render --audit-layout for a final-state screenshot and --film --audit-layout for motion. Declare important selectors, a content frame and reserved footer/subtitle rectangles; exclude intentional stamps/background overlays. Text Range bounds reflect loaded fonts and actual Canvas scaling. Canvas exposes its existing engine-clock camera, drift midpoint/end and sequence-waypoint deadlines only as DOM diagnostic hints; static/jump/exploration states do not claim future motion. A later step can interrupt a phase, and masks/rotation or hidden content remain unknown rather than "visible". Inspect evidence before changing intentional overlap.
|
|
235
|
+
|
|
200
236
|
Common pitfall: For visual explainers, read npx joplo skill content: keep a continuous visual story, storyboard every chapter, film-strip the chain, and verify playback before claiming it works`;
|
package/dist/plugin.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
/** 进退场预设(D92):每个预设是一个“离场姿态”,进场 = 离场姿态 → 原样,退场 = 原样 → 离场姿态。 */
|
|
3
|
-
export declare const TRANSITIONS: readonly ["fade", "rise", "zoom", "shrink", "wipe", "iris"];
|
|
3
|
+
export declare const TRANSITIONS: readonly ["fade", "rise", "zoom", "shrink", "wipe", "iris", "grow", "growUp", "blur"];
|
|
4
4
|
export type Transition = (typeof TRANSITIONS)[number];
|
|
5
|
+
/** 缓动预设:进场、退场、变形各自的“怎么落定”。smooth = 各自的默认曲线;spring / bounce 会冲过终点再回来。 */
|
|
6
|
+
export declare const EASES: readonly ["smooth", "snappy", "spring", "bounce", "linear"];
|
|
7
|
+
export type Ease = (typeof EASES)[number];
|
|
8
|
+
/** <Split by>:按词(Intl.Segmenter,中文也能切成词)或按字拆开,逐块进场。 */
|
|
9
|
+
export declare const SPLITS: readonly ["word", "char"];
|
|
5
10
|
/** 镜头漂移(D92):落定后继续缓慢推近 / 拉远 / 平移,有终点、非匀速。数字 = 在 ms 内再推近到这个倍数。 */
|
|
6
11
|
export type Drift = number | false | {
|
|
7
12
|
zoom?: number;
|
|
@@ -23,6 +28,16 @@ export declare const DriftSchema: z.ZodUnion<readonly [z.ZodLiteral<false>, z.Zo
|
|
|
23
28
|
y: z.ZodOptional<z.ZodNumber>;
|
|
24
29
|
ms: z.ZodOptional<z.ZodNumber>;
|
|
25
30
|
}, z.core.$strict>]>;
|
|
31
|
+
export type CameraWaypoint = {
|
|
32
|
+
atMs: number;
|
|
33
|
+
target?: string;
|
|
34
|
+
targets?: string[];
|
|
35
|
+
pad?: number;
|
|
36
|
+
zoom?: number;
|
|
37
|
+
ease?: 'easeInOut' | 'easeOut' | 'linear';
|
|
38
|
+
};
|
|
39
|
+
/** Explicit state-to-state camera waypoints, milliseconds from this step commit. */
|
|
40
|
+
export declare const cameraSequence: (points: CameraWaypoint[]) => import("@joplo-app/kit/plugin").PluginEffectDef;
|
|
26
41
|
declare const Frame: z.ZodObject<{
|
|
27
42
|
scenes: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
28
43
|
camera: z.ZodObject<{
|
|
@@ -36,10 +51,23 @@ declare const Frame: z.ZodObject<{
|
|
|
36
51
|
y: z.ZodOptional<z.ZodNumber>;
|
|
37
52
|
ms: z.ZodOptional<z.ZodNumber>;
|
|
38
53
|
}, z.core.$strict>]>>;
|
|
54
|
+
sequence: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
55
|
+
targets: z.ZodArray<z.ZodString>;
|
|
56
|
+
zoom: z.ZodOptional<z.ZodNumber>;
|
|
57
|
+
pad: z.ZodOptional<z.ZodNumber>;
|
|
58
|
+
atMs: z.ZodNumber;
|
|
59
|
+
ease: z.ZodOptional<z.ZodEnum<{
|
|
60
|
+
linear: "linear";
|
|
61
|
+
easeInOut: "easeInOut";
|
|
62
|
+
easeOut: "easeOut";
|
|
63
|
+
}>>;
|
|
64
|
+
}, z.core.$strict>>>;
|
|
65
|
+
sequenceId: z.ZodOptional<z.ZodNumber>;
|
|
39
66
|
}, z.core.$strict>;
|
|
40
67
|
}, z.core.$strict>>;
|
|
41
68
|
}, z.core.$strict>;
|
|
42
69
|
export type ContentFrame = z.infer<typeof Frame>;
|
|
43
70
|
declare const content: import("@joplo-app/kit").PluginDef;
|
|
44
71
|
export declare const Canvas: (props: import("@joplo-app/kit").JoploProps) => any;
|
|
72
|
+
export declare const Split: (props: import("@joplo-app/kit").JoploProps) => any;
|
|
45
73
|
export default content;
|
package/dist/plugin.js
CHANGED
|
@@ -4,7 +4,11 @@ import { definePlugin, pluginComponent, pluginEffect } from '@joplo-app/kit/plug
|
|
|
4
4
|
import { studio } from "./theme.js";
|
|
5
5
|
import { skill, patterns } from "./guide.js";
|
|
6
6
|
/** 进退场预设(D92):每个预设是一个“离场姿态”,进场 = 离场姿态 → 原样,退场 = 原样 → 离场姿态。 */
|
|
7
|
-
export const TRANSITIONS = ['fade', 'rise', 'zoom', 'shrink', 'wipe', 'iris'];
|
|
7
|
+
export const TRANSITIONS = ['fade', 'rise', 'zoom', 'shrink', 'wipe', 'iris', 'grow', 'growUp', 'blur'];
|
|
8
|
+
/** 缓动预设:进场、退场、变形各自的“怎么落定”。smooth = 各自的默认曲线;spring / bounce 会冲过终点再回来。 */
|
|
9
|
+
export const EASES = ['smooth', 'snappy', 'spring', 'bounce', 'linear'];
|
|
10
|
+
/** <Split by>:按词(Intl.Segmenter,中文也能切成词)或按字拆开,逐块进场。 */
|
|
11
|
+
export const SPLITS = ['word', 'char'];
|
|
8
12
|
/** Move within the design world; no ids restores the whole world. This factory has no player semantics. */
|
|
9
13
|
export const camera = (...args) => {
|
|
10
14
|
const targets = args.filter((arg) => typeof arg === 'string');
|
|
@@ -13,13 +17,24 @@ export const camera = (...args) => {
|
|
|
13
17
|
};
|
|
14
18
|
export const DriftSchema = z.union([z.literal(false), z.number().min(.5).max(2), z.strictObject({ zoom: z.number().min(.5).max(2).optional(), x: z.number().min(-2000).max(2000).optional(), y: z.number().min(-2000).max(2000).optional(), ms: z.number().min(500).max(60000).optional() })]);
|
|
15
19
|
const Safe = z.tuple([z.number().min(0).max(2000), z.number().min(0).max(2000), z.number().min(0).max(2000), z.number().min(0).max(2000)]);
|
|
16
|
-
const
|
|
20
|
+
const CameraBase = z.strictObject({ targets: z.array(z.string()), pad: z.number().min(0).max(2000).optional(), zoom: z.number().min(.1).max(10).optional(), ms: z.number().min(0).max(10000).optional(), drift: DriftSchema.optional() });
|
|
21
|
+
const Waypoint = CameraBase.omit({ ms: true, drift: true }).extend({ atMs: z.number().min(0).max(60000), ease: z.enum(['easeInOut', 'easeOut', 'linear']).optional() });
|
|
22
|
+
const Camera = CameraBase.extend({ sequence: z.array(Waypoint).min(2).max(32).optional(), sequenceId: z.number().int().nonnegative().optional() });
|
|
23
|
+
/** Explicit state-to-state camera waypoints, milliseconds from this step commit. */
|
|
24
|
+
export const cameraSequence = (points) => pluginEffect('content', 'camera', {
|
|
25
|
+
targets: points.at(-1)?.targets ?? (points.at(-1)?.target ? [points.at(-1).target] : []),
|
|
26
|
+
drift: false,
|
|
27
|
+
sequence: points.map(({ target, targets, ...p }) => ({ ...p, targets: targets ?? (target ? [target] : []) })),
|
|
28
|
+
});
|
|
17
29
|
const Frame = z.strictObject({ scenes: z.record(z.string(), z.strictObject({ camera: Camera })) });
|
|
18
30
|
const all = (n) => [n, ...(n.children ?? []).flatMap(all)];
|
|
19
31
|
const content = definePlugin({ skillTopics: { patterns: { description: 'Recipes and individual pitfalls', body: patterns } }, packageName: '@joplo-app/plugin-content',
|
|
20
32
|
id: 'content', title: 'Visual explainers', version: packageInfo.version,
|
|
21
33
|
runtime: new URL(import.meta.url.endsWith('.ts') ? './runtime.tsx' : './runtime.js', import.meta.url),
|
|
22
|
-
components: {
|
|
34
|
+
components: {
|
|
35
|
+
Canvas: { doc: 'w, h, view=[1280,800], drift?, safe?=[top,right,bottom,left]; scaled design world with fixed screen children; drift = default camera drift; safe = the view area not covered by screen chrome, where targeted camera() frames land', selfEvident: true },
|
|
36
|
+
Split: { doc: 'text, by="word"|"char"; text that enters piece by piece: enter / enterMs / enterEase apply to each piece, enterStagger (default word 70, char 30 ms) spaces them; screen readers get the whole text', example: '<Split text="It is not typing, it is guessing" enter="rise" enterEase="spring" />', traits: { text: ['text'] }, selfEvident: true },
|
|
37
|
+
},
|
|
23
38
|
properties: {
|
|
24
39
|
motion: { type: 'string', nonempty: true, attribute: 'data-jp-content-motion' },
|
|
25
40
|
motionDelay: { type: 'number', min: 0, max: 10000, attribute: 'data-jp-content-motion-delay' },
|
|
@@ -31,12 +46,28 @@ const content = definePlugin({ skillTopics: { patterns: { description: 'Recipes
|
|
|
31
46
|
exit: { type: 'string', values: [...TRANSITIONS], attribute: 'data-jp-content-exit' },
|
|
32
47
|
exitMs: { type: 'number', min: 0, max: 10000, attribute: 'data-jp-content-exit-ms' },
|
|
33
48
|
exitDelay: { type: 'number', min: 0, max: 10000, attribute: 'data-jp-content-exit-delay' },
|
|
49
|
+
enterEase: { type: 'string', values: [...EASES], attribute: 'data-jp-content-enter-ease' },
|
|
50
|
+
exitEase: { type: 'string', values: [...EASES], attribute: 'data-jp-content-exit-ease' },
|
|
51
|
+
motionEase: { type: 'string', values: [...EASES], attribute: 'data-jp-content-motion-ease' },
|
|
52
|
+
enterStagger: { type: 'number', min: 0, max: 2000, attribute: 'data-jp-content-enter-stagger' },
|
|
53
|
+
exitStagger: { type: 'number', min: 0, max: 2000, attribute: 'data-jp-content-exit-stagger' },
|
|
34
54
|
},
|
|
35
55
|
themes: { studio }, skill,
|
|
36
|
-
schemas: { step: Frame },
|
|
37
|
-
data: { step: { scope: [{ path: ['scenes'], kind: 'map', domain: 'scene', children: [{ path: ['camera', 'targets'], kind: 'values', domain: 'element' }] }] } },
|
|
56
|
+
schemas: { step: z.union([Frame, z.strictObject({ cameraIssued: z.literal(true) })]) },
|
|
57
|
+
data: { step: { scope: [{ path: ['scenes'], kind: 'map', domain: 'scene', children: [{ path: ['camera', 'targets'], kind: 'values', domain: 'element' }, { path: ['camera', 'sequence', '*', 'targets'], kind: 'values', domain: 'element' }] }] } },
|
|
38
58
|
compile: {
|
|
39
59
|
node(node, ctx) {
|
|
60
|
+
if (node.type === 'content:Split') {
|
|
61
|
+
const text = node.props?.text;
|
|
62
|
+
// 绑定状态($.ui.title)在这里不是字符串;只拦没写、空白和数字 / 布尔字面量
|
|
63
|
+
if (text === undefined || text === null || (typeof text === 'string' ? !text.trim() : typeof text === 'number' || typeof text === 'boolean'))
|
|
64
|
+
ctx.report('SPLIT_INVALID', '<Split text>: write the text to split as a nonempty string (it may be a state binding like $.ui.title)', node.source);
|
|
65
|
+
if (node.props?.by !== undefined && !SPLITS.includes(node.props.by))
|
|
66
|
+
ctx.report('SPLIT_INVALID', `<Split by>: use one of ${SPLITS.join(', ')}`, node.source);
|
|
67
|
+
if (node.children?.length)
|
|
68
|
+
ctx.report('SPLIT_INVALID', '<Split>: put the text in the text prop, not in children', node.source);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
40
71
|
if (node.type !== 'content:Canvas')
|
|
41
72
|
return;
|
|
42
73
|
if (node.props.drift !== undefined && !DriftSchema.safeParse(node.props.drift).success)
|
|
@@ -55,15 +86,22 @@ const content = definePlugin({ skillTopics: { patterns: { description: 'Recipes
|
|
|
55
86
|
return;
|
|
56
87
|
}
|
|
57
88
|
const value = parsed.data;
|
|
89
|
+
if (value.sequence && (value.sequence[0].atMs !== 0 || value.sequence.some((p, i, a) => i > 0 && p.atMs <= a[i - 1].atMs))) {
|
|
90
|
+
ctx.report('CAMERA_INVALID', 'cameraSequence starts at 0 and needs strictly increasing atMs', ctx.source);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const targets = [...value.targets, ...value.sequence?.flatMap(p => p.targets) ?? []];
|
|
58
94
|
const nodes = ctx.roots.flatMap(all);
|
|
59
|
-
const missing =
|
|
95
|
+
const missing = targets.filter(id => !nodes.some(n => n.id === id));
|
|
60
96
|
if (missing.length) {
|
|
61
97
|
ctx.report('CAMERA_UNKNOWN', `camera(${missing.map(m => JSON.stringify(m)).join(', ')}) target is not in any layer or the stage for this step; aim it at elements inside a <Canvas>`, ctx.source);
|
|
62
98
|
return;
|
|
63
99
|
}
|
|
64
100
|
return {
|
|
65
101
|
writes: [{ path: 'ui.__plugins.content.camera', value }],
|
|
66
|
-
|
|
102
|
+
data: { cameraIssued: true },
|
|
103
|
+
references: targets,
|
|
104
|
+
...(value.sequence ? { holdMs: value.sequence.at(-1).atMs } : {}),
|
|
67
105
|
...(value.targets.length ? { directorTarget: value.targets[0] } : {}),
|
|
68
106
|
};
|
|
69
107
|
},
|
|
@@ -77,9 +115,10 @@ const content = definePlugin({ skillTopics: { patterns: { description: 'Recipes
|
|
|
77
115
|
ctx.report('CAMERA_INVALID', 'Invalid content camera state; use camera() with valid settings');
|
|
78
116
|
return;
|
|
79
117
|
}
|
|
80
|
-
return { scenes: Object.fromEntries(scenes.map(s => [s.id, { camera: { ...parsed.data, targets: parsed.data.targets.filter(id => all(s.root).some(n => n.id === id)) } }])) };
|
|
118
|
+
return { scenes: Object.fromEntries(scenes.map(s => [s.id, { camera: { ...parsed.data, ...(parsed.data.sequence ? { sequenceId: ctx.position === 0 ? 0 : ctx.data?.cameraIssued ? ctx.position : ctx.previousData?.scenes[s.id]?.camera.sequenceId ?? 0 } : {}), targets: parsed.data.targets.filter(id => all(s.root).some(n => n.id === id)) } }])) };
|
|
81
119
|
},
|
|
82
120
|
},
|
|
83
121
|
});
|
|
84
122
|
export const Canvas = pluginComponent(content, 'Canvas');
|
|
123
|
+
export const Split = pluginComponent(content, 'Split');
|
|
85
124
|
export default content;
|
package/dist/runtime.d.ts
CHANGED
|
@@ -59,6 +59,12 @@ export declare function cameraAt(seg: CameraSegment, t: number, view: {
|
|
|
59
59
|
cx?: number;
|
|
60
60
|
cy?: number;
|
|
61
61
|
}): Frame;
|
|
62
|
+
/** Pure, clamped waypoint projection; each easing belongs to the destination waypoint. */
|
|
63
|
+
export declare function sequenceFrameAt(points: {
|
|
64
|
+
atMs: number;
|
|
65
|
+
frame: Frame;
|
|
66
|
+
ease?: string;
|
|
67
|
+
}[], elapsedMs: number): Frame;
|
|
62
68
|
/** camera(…, { drift }) 优先,其次 <Canvas drift>,都没写时用 DEFAULT_DRIFT;false 关闭。 */
|
|
63
69
|
export declare function driftOf(camera: unknown, canvas: unknown): DriftSpec | null;
|
|
64
70
|
type Mark = {
|
|
@@ -82,6 +88,28 @@ export declare function jumpedSince(last: Mark | null, f: {
|
|
|
82
88
|
* 用单个关键帧(另一端是元素的底层样式),不覆盖作者自己的 opacity / transform。
|
|
83
89
|
*/
|
|
84
90
|
export declare const AWAY: Record<string, Keyframe>;
|
|
91
|
+
/**
|
|
92
|
+
* 阻尼弹簧从 0 到 1 的位置。时间归一化:t = 1 时振幅包络衰减到千分之一(视觉上已落定),
|
|
93
|
+
* 所以作者写的 ms 就是弹簧的总时长。zeta 是阻尼比:越小冲得越远、晃得越多。
|
|
94
|
+
*/
|
|
95
|
+
export declare function springAt(zeta: number, t: number): number;
|
|
96
|
+
/** 把弹簧采样成 CSS linear() 缓动:WAAPI 直接用,引擎时钟照常采样(暂停、跳转、导出都一致)。 */
|
|
97
|
+
export declare function springEasing(zeta: number, samples?: number): string;
|
|
98
|
+
/** 缓动预设 → CSS 缓动;没写或 smooth 用这一类动画自己的默认曲线。 */
|
|
99
|
+
export declare function easeOf(preset: string | undefined, fallback: string): string;
|
|
100
|
+
/** 错峰:同一个容器里这一次一起出现(或一起离开)的元素,第 rank 个多等 rank × stagger 毫秒。 */
|
|
101
|
+
export declare function staggered(ranks: Map<Element, number>, host: Element | null, attr: 'enterStagger' | 'exitStagger'): number;
|
|
102
|
+
/**
|
|
103
|
+
* <Split> 的拆法:返回一串“组”,字符串是原样保留的空白,数组是一个不断行的词(里面每一项是一块,逐块进场)。
|
|
104
|
+
* word:Intl.Segmenter 按词切(中文也能切成词),标点贴在前一个词后面,行首不会出现孤立的标点。
|
|
105
|
+
* char:先按词分组(词内不断行),组内按字形(emoji、组合字符不拆)一块一块。
|
|
106
|
+
*/
|
|
107
|
+
export declare function splitPieces(text: string, by?: 'word' | 'char'): (string | string[])[];
|
|
108
|
+
/**
|
|
109
|
+
* 外观指纹:去掉身份与 Joplo 锚点属性(id、data-j*、aria-*)后的标记。同一个 motion 键前后指纹不同(换了 class、
|
|
110
|
+
* 内联样式、内部结构或文字)时,旧样子要跟着飞并淡出,不能只插值键元素自己的几个样式(内层的底色、斜面边框会跳变)。
|
|
111
|
+
*/
|
|
112
|
+
export declare function lookKey(el: Element): string;
|
|
85
113
|
/** One observer per stage: cache only design-space layouts, never player state. */
|
|
86
114
|
export declare const observe: PluginObserve;
|
|
87
115
|
declare const _default: import("@joplo-app/kit/plugin").PluginRuntime;
|
package/dist/runtime.js
CHANGED
|
@@ -3,6 +3,20 @@ import { useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
|
3
3
|
import { defineRuntime } from '@joplo-app/kit/plugin';
|
|
4
4
|
import { useEngineFrame, useRoot } from '@joplo-app/kit/renderer';
|
|
5
5
|
const stillCss = '.jstage[data-jstill] [data-jcanvas],.jstage[data-jstill] [data-jcanvas] *{transition:none!important;animation-delay:0s!important;animation-duration:0s!important}';
|
|
6
|
+
const subjectStyle = (el) => {
|
|
7
|
+
// Read the authored destination, not this observer's currently interpolated style.
|
|
8
|
+
const active = (el.getAnimations?.() ?? []).filter(a => a.id === 'jmotion').map(a => ({ a, effect: a.effect }));
|
|
9
|
+
for (const { a } of active)
|
|
10
|
+
a.effect = null;
|
|
11
|
+
try {
|
|
12
|
+
const c = getComputedStyle(el);
|
|
13
|
+
return { borderRadius: c.borderRadius, color: c.color, backgroundColor: c.backgroundColor, opacity: c.opacity };
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
for (const { a, effect } of active)
|
|
17
|
+
a.effect = effect;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
6
20
|
/** 元素在画布世界里的布局位置(offset 链,不受镜头和变形动画的 transform 影响);不在 root 里时为 null。 */
|
|
7
21
|
function offsetIn(el, root) {
|
|
8
22
|
let x = 0;
|
|
@@ -93,6 +107,20 @@ export function cameraAt(seg, t, view) {
|
|
|
93
107
|
const q = driftEase(Math.max(0, Math.min(1, (t - seg.start - seg.ms) / seg.drift.ms)));
|
|
94
108
|
return q > 0 ? drifted(seg.to, seg.drift, q, view) : seg.to;
|
|
95
109
|
}
|
|
110
|
+
/** Pure, clamped waypoint projection; each easing belongs to the destination waypoint. */
|
|
111
|
+
export function sequenceFrameAt(points, elapsedMs) {
|
|
112
|
+
if (elapsedMs <= points[0].atMs)
|
|
113
|
+
return points[0].frame;
|
|
114
|
+
for (let i = 1; i < points.length; i++) {
|
|
115
|
+
const b = points[i], a = points[i - 1];
|
|
116
|
+
if (elapsedMs > b.atMs)
|
|
117
|
+
continue;
|
|
118
|
+
const t = Math.max(0, Math.min(1, (elapsedMs - a.atMs) / (b.atMs - a.atMs)));
|
|
119
|
+
const q = b.ease === 'linear' ? t : b.ease === 'easeOut' ? 1 - (1 - t) ** 3 : cameraEase(t);
|
|
120
|
+
return { k: a.frame.k + (b.frame.k - a.frame.k) * q, tx: a.frame.tx + (b.frame.tx - a.frame.tx) * q, ty: a.frame.ty + (b.frame.ty - a.frame.ty) * q };
|
|
121
|
+
}
|
|
122
|
+
return points.at(-1).frame;
|
|
123
|
+
}
|
|
96
124
|
/** camera(…, { drift }) 优先,其次 <Canvas drift>,都没写时用 DEFAULT_DRIFT;false 关闭。 */
|
|
97
125
|
export function driftOf(camera, canvas) {
|
|
98
126
|
const v = camera !== undefined ? camera : canvas !== undefined ? canvas : DEFAULT_DRIFT;
|
|
@@ -154,17 +182,26 @@ function Canvas({ ctx: context }) {
|
|
|
154
182
|
const whole = canvasFrame({ x: 0, y: 0, ...world }, view, Infinity);
|
|
155
183
|
const clock = ctx.clock;
|
|
156
184
|
// 引擎时钟驱动(D92):镜头的每一段从“此刻实际的取景”出发,落定后按 drift 漂移;没有时钟的宿主退回 CSS 过渡、不漂移
|
|
157
|
-
const
|
|
185
|
+
const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
186
|
+
const timed = !!clock && ctx.animate && !reduced;
|
|
158
187
|
const now = clock?.timeMs ?? 0;
|
|
159
188
|
const seg = useRef({ from: whole, to: whole, start: now, ms: 0, drift: null });
|
|
160
189
|
const [, redraw] = useState(0);
|
|
161
190
|
const lastMark = useRef(null);
|
|
162
191
|
const target = useRef(whole);
|
|
163
192
|
const driftKey = useRef('');
|
|
193
|
+
const pathRef = useRef(null);
|
|
164
194
|
useLayoutEffect(() => {
|
|
165
195
|
const w = worldRef.current;
|
|
166
196
|
if (!w)
|
|
167
197
|
return;
|
|
198
|
+
const frameFor = (ids, pad = 48, zoom = 3) => {
|
|
199
|
+
const boxes = ids.flatMap(id => { const el = w.querySelector(`[data-jid="${CSS.escape(id)}"]`); const b = el ? offsetIn(el, w) : null; return b ? [b] : []; });
|
|
200
|
+
if (!boxes.length)
|
|
201
|
+
return whole;
|
|
202
|
+
const x = Math.min(...boxes.map(b => b.x)) - pad, y = Math.min(...boxes.map(b => b.y)) - pad;
|
|
203
|
+
return canvasFrame({ x, y, w: Math.max(...boxes.map(b => b.x + b.w)) + pad - x, h: Math.max(...boxes.map(b => b.y + b.h)) + pad - y }, view, zoom, safe);
|
|
204
|
+
};
|
|
168
205
|
// 1) 取景:目标的布局范围(offset,不含 transform)合起来,加留白
|
|
169
206
|
let next = whole;
|
|
170
207
|
const ids = cam?.targets ?? [];
|
|
@@ -183,6 +220,13 @@ function Canvas({ ctx: context }) {
|
|
|
183
220
|
next = canvasFrame({ x: x0, y: y0, w: x1 - x0, h: y1 - y0 }, view, cam?.zoom ?? 3, safe);
|
|
184
221
|
}
|
|
185
222
|
}
|
|
223
|
+
const pathKey = JSON.stringify([ctx.scenarioId, cam?.sequenceId, cam?.sequence ?? null]);
|
|
224
|
+
if (cam?.sequence && (pathRef.current?.key !== pathKey || jumpedSince(lastMark.current, ctx))) {
|
|
225
|
+
const live = (cam.sequenceId ?? 0) > 0 && timed && !!clock?.running && lastMark.current !== null && !jumpedSince(lastMark.current, ctx) && !ctx.playground;
|
|
226
|
+
pathRef.current = { key: pathKey, start: live ? now : now - cam.sequence.at(-1).atMs, frames: cam.sequence.map(p => ({ atMs: p.atMs, frame: frameFor(p.targets, p.pad, p.zoom), ease: p.ease })) };
|
|
227
|
+
}
|
|
228
|
+
else if (!cam?.sequence)
|
|
229
|
+
pathRef.current = null;
|
|
186
230
|
const drift = timed ? driftOf(cam?.drift, canvasDrift) : null;
|
|
187
231
|
const dk = JSON.stringify(drift);
|
|
188
232
|
const camMoves = !same(target.current, next);
|
|
@@ -214,9 +258,12 @@ function Canvas({ ctx: context }) {
|
|
|
214
258
|
const s = box.w && box.h ? Math.min(box.w / view.w, box.h / view.h) : 0;
|
|
215
259
|
const ox = (box.w - view.w * s) / 2;
|
|
216
260
|
const oy = (box.h - view.h * s) / 2;
|
|
217
|
-
const frame = timed ? cameraAt(seg.current, now, lensView) : seg.current.to;
|
|
261
|
+
const frame = cam?.sequence && pathRef.current ? sequenceFrameAt(pathRef.current.frames, !timed || ctx.playground || !clock?.running && !clock?.paused ? Infinity : now - pathRef.current.start) : timed ? cameraAt(seg.current, now, lensView) : seg.current.to;
|
|
218
262
|
const ms = cam?.ms ?? 1200;
|
|
219
|
-
return (_jsxs("div", { ...root, children: [_jsx("style", { children: stillCss }), _jsxs("div", { ref: outer, style: { position: 'absolute', inset: 0 }, "data-jcanvas": "", "data-jreport-surface": "Canvas",
|
|
263
|
+
return (_jsxs("div", { ...root, children: [_jsx("style", { children: stillCss }), _jsxs("div", { ref: outer, style: { position: 'absolute', inset: 0 }, "data-jcanvas": "", "data-jreport-surface": "Canvas", "data-joplo-audit-phases": timed && !ctx.playground && (clock?.running || clock?.paused) ? JSON.stringify({ clockMs: now, phases: pathRef.current
|
|
264
|
+
? pathRef.current.frames.map(point => ({ phase: 'camera-waypoint', atMs: pathRef.current.start + point.atMs }))
|
|
265
|
+
: [{ phase: 'camera-end', atMs: seg.current.start + seg.current.ms }, ...(seg.current.drift ? [{ phase: 'drift-mid', atMs: seg.current.start + seg.current.ms + seg.current.drift.ms / 2 }, { phase: 'drift-end', atMs: seg.current.start + seg.current.ms + seg.current.drift.ms }] : [])],
|
|
266
|
+
}) : undefined, children: [_jsx("div", { ref: worldRef, "data-jcanvas-world": "", "data-jreport-viewport": "", style: {
|
|
220
267
|
position: 'absolute', left: 0, top: 0, width: world.w, height: world.h, transformOrigin: '0 0',
|
|
221
268
|
visibility: s ? 'visible' : 'hidden',
|
|
222
269
|
transform: `translate(${ox + frame.tx * s}px, ${oy + frame.ty * s}px) scale(${frame.k * s})`,
|
|
@@ -234,12 +281,61 @@ export const AWAY = {
|
|
|
234
281
|
shrink: { opacity: 0, scale: '.84' },
|
|
235
282
|
wipe: { clipPath: 'inset(0 100% 0 0)' },
|
|
236
283
|
iris: { clipPath: 'circle(0% at 50% 50%)' },
|
|
284
|
+
/** 从 0 长出来:grow 从左边横向长(横条、时间轴线、下划线),growUp 从底边往上长(柱子)。方向写明,不按宽高猜(很短的横条比它的高还窄)。 */
|
|
285
|
+
grow: { scale: '0 1', transformOrigin: '0 50%' },
|
|
286
|
+
growUp: { scale: '1 0', transformOrigin: '50% 100%' },
|
|
287
|
+
blur: { opacity: 0, filter: 'blur(14px)' },
|
|
237
288
|
};
|
|
289
|
+
/** Grow anchors stay fixed throughout the flight; an omitted endpoint would interpolate back to center. */
|
|
290
|
+
function transitionFrames(away, entering) {
|
|
291
|
+
const anchor = away.transformOrigin === undefined ? [] : [{ transformOrigin: away.transformOrigin, offset: entering ? 1 : 0 }];
|
|
292
|
+
return entering ? [{ ...away, offset: 0 }, ...anchor] : [...anchor, { ...away, offset: 1 }];
|
|
293
|
+
}
|
|
238
294
|
const ENTER_EASE = 'cubic-bezier(.16,1,.3,1)';
|
|
239
295
|
const EXIT_EASE = 'cubic-bezier(.55,0,.75,.2)';
|
|
240
296
|
const ENTER_MS = 600;
|
|
241
297
|
const EXIT_MS = 450;
|
|
242
298
|
const msOf = (v, d) => (v === undefined || v === '' || !Number.isFinite(Number(v)) ? d : Math.max(0, Number(v)));
|
|
299
|
+
/**
|
|
300
|
+
* 阻尼弹簧从 0 到 1 的位置。时间归一化:t = 1 时振幅包络衰减到千分之一(视觉上已落定),
|
|
301
|
+
* 所以作者写的 ms 就是弹簧的总时长。zeta 是阻尼比:越小冲得越远、晃得越多。
|
|
302
|
+
*/
|
|
303
|
+
export function springAt(zeta, t) {
|
|
304
|
+
if (t <= 0)
|
|
305
|
+
return 0;
|
|
306
|
+
if (t >= 1)
|
|
307
|
+
return 1;
|
|
308
|
+
const w = Math.log(1000) / zeta;
|
|
309
|
+
const wd = w * Math.sqrt(1 - zeta * zeta);
|
|
310
|
+
return 1 - Math.exp(-zeta * w * t) * (Math.cos(wd * t) + (zeta * w / wd) * Math.sin(wd * t));
|
|
311
|
+
}
|
|
312
|
+
/** 把弹簧采样成 CSS linear() 缓动:WAAPI 直接用,引擎时钟照常采样(暂停、跳转、导出都一致)。 */
|
|
313
|
+
export function springEasing(zeta, samples = 60) {
|
|
314
|
+
const pts = Array.from({ length: samples + 1 }, (_, i) => (i === samples ? 1 : springAt(zeta, i / samples)));
|
|
315
|
+
return `linear(${pts.map(v => String(Math.round(v * 10000) / 10000)).join(', ')})`;
|
|
316
|
+
}
|
|
317
|
+
/** 不支持 linear() 的浏览器(el.animate 会因非法缓动抛错)退回一条略冲过终点的贝塞尔。 */
|
|
318
|
+
const linearOk = () => typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('animation-timing-function', 'linear(0, 1)');
|
|
319
|
+
const EASE_CURVES = {
|
|
320
|
+
snappy: () => 'cubic-bezier(.05,.7,.1,1)',
|
|
321
|
+
linear: () => 'linear',
|
|
322
|
+
spring: () => (linearOk() ? springEasing(.5) : 'cubic-bezier(.34,1.4,.64,1)'),
|
|
323
|
+
bounce: () => (linearOk() ? springEasing(.32) : 'cubic-bezier(.34,1.8,.64,1)'),
|
|
324
|
+
};
|
|
325
|
+
/** 缓动预设 → CSS 缓动;没写或 smooth 用这一类动画自己的默认曲线。 */
|
|
326
|
+
export function easeOf(preset, fallback) {
|
|
327
|
+
const curve = preset && preset !== 'smooth' ? EASE_CURVES[preset] : undefined;
|
|
328
|
+
return curve ? curve() : fallback;
|
|
329
|
+
}
|
|
330
|
+
/** 错峰:同一个容器里这一次一起出现(或一起离开)的元素,第 rank 个多等 rank × stagger 毫秒。 */
|
|
331
|
+
export function staggered(ranks, host, attr) {
|
|
332
|
+
if (!(host instanceof HTMLElement))
|
|
333
|
+
return 0;
|
|
334
|
+
const step = msOf(host.dataset[attr === 'enterStagger' ? 'jpContentEnterStagger' : 'jpContentExitStagger'], 0);
|
|
335
|
+
const rank = ranks.get(host) ?? 0;
|
|
336
|
+
ranks.set(host, rank + 1);
|
|
337
|
+
return rank * step;
|
|
338
|
+
}
|
|
243
339
|
/** 幽灵不带身份:不能被镜头、FLIP、检查、提示、无障碍树或键盘找到。 */
|
|
244
340
|
const IDENTITY = ['id', 'name', 'for', 'tabindex', 'autofocus', 'contenteditable', 'data-jid', 'data-jinteractive', 'data-jhover'];
|
|
245
341
|
function strip(el) {
|
|
@@ -272,6 +368,80 @@ function copyLive(from, to) {
|
|
|
272
368
|
}
|
|
273
369
|
});
|
|
274
370
|
}
|
|
371
|
+
/**
|
|
372
|
+
* <Split> 的拆法:返回一串“组”,字符串是原样保留的空白,数组是一个不断行的词(里面每一项是一块,逐块进场)。
|
|
373
|
+
* word:Intl.Segmenter 按词切(中文也能切成词),标点贴在前一个词后面,行首不会出现孤立的标点。
|
|
374
|
+
* char:先按词分组(词内不断行),组内按字形(emoji、组合字符不拆)一块一块。
|
|
375
|
+
*/
|
|
376
|
+
export function splitPieces(text, by = 'word') {
|
|
377
|
+
const Seg = Intl.Segmenter;
|
|
378
|
+
const words = [];
|
|
379
|
+
const raw = Seg ? [...new Seg(undefined, { granularity: 'word' }).segment(text)] : text.split(/(\s+)/).filter(Boolean).map(segment => ({ segment, isWordLike: !/^\s+$/.test(segment) }));
|
|
380
|
+
let lead = '';
|
|
381
|
+
for (const { segment, isWordLike } of raw) {
|
|
382
|
+
const space = /^\s+$/.test(segment);
|
|
383
|
+
const prev = words[words.length - 1];
|
|
384
|
+
// 开括号、开引号贴到后一个词上;其余标点(不是词也不是空白)贴到前一个词上
|
|
385
|
+
if (!space && !isWordLike && /^[\p{Ps}\p{Pi}]+$/u.test(segment)) {
|
|
386
|
+
lead += segment;
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
if (!space && !isWordLike && !lead && prev && !prev.space) {
|
|
390
|
+
prev.s += segment;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (space) {
|
|
394
|
+
if (lead) {
|
|
395
|
+
words.push({ s: lead, space: false });
|
|
396
|
+
lead = '';
|
|
397
|
+
}
|
|
398
|
+
words.push({ s: segment, space });
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
words.push({ s: lead + segment, space: false });
|
|
402
|
+
lead = '';
|
|
403
|
+
}
|
|
404
|
+
if (lead)
|
|
405
|
+
words.push({ s: lead, space: false });
|
|
406
|
+
const graphemes = (s) => (Seg ? [...new Seg(undefined, { granularity: 'grapheme' }).segment(s)].map(g => g.segment) : Array.from(s));
|
|
407
|
+
return words.map(w => (w.space ? w.s : by === 'char' ? graphemes(w.s) : [w.s]));
|
|
408
|
+
}
|
|
409
|
+
const SPLIT_STAGGER = { word: 70, char: 30 };
|
|
410
|
+
const SR_ONLY = { position: 'absolute', width: 1, height: 1, margin: -1, padding: 0, overflow: 'hidden', clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap', border: 0 };
|
|
411
|
+
const PIECE_ATTRS = ['data-jp-content-enter', 'data-jp-content-enter-ms', 'data-jp-content-enter-delay', 'data-jp-content-enter-ease'];
|
|
412
|
+
/** 逐块进场的文字:进场属性写在每一块上(根元素自己不进场),根元素上的 enterStagger 决定间隔;读屏读整句。 */
|
|
413
|
+
function Split({ ctx: context }) {
|
|
414
|
+
const p = context.node.props;
|
|
415
|
+
const text = p.text === undefined || p.text === null ? '' : String(p.text);
|
|
416
|
+
const by = p.by === 'char' ? 'char' : 'word';
|
|
417
|
+
const { text: _t, by: _b, ...rest } = p;
|
|
418
|
+
const root = useRoot(context.model, rest, {});
|
|
419
|
+
const piece = { 'data-jp-content-enter': 'rise' };
|
|
420
|
+
for (const a of PIECE_ATTRS)
|
|
421
|
+
if (root[a] !== undefined) {
|
|
422
|
+
piece[a] = root[a];
|
|
423
|
+
delete root[a];
|
|
424
|
+
}
|
|
425
|
+
root['data-jp-content-enter-stagger'] ??= String(SPLIT_STAGGER[by]);
|
|
426
|
+
const groups = useMemo(() => splitPieces(text, by), [text, by]);
|
|
427
|
+
let n = 0;
|
|
428
|
+
return (_jsxs("span", { ...root, children: [_jsx("span", { style: SR_ONLY, children: text }), _jsx("span", { "aria-hidden": "true", children: groups.map((g, i) => typeof g === 'string' ? g : (_jsx("span", { style: { display: 'inline-block', whiteSpace: 'nowrap' }, children: g.map(c => _jsx("span", { ...piece, style: { display: 'inline-block', whiteSpace: 'pre' }, children: (n++, c) }, n)) }, `${text}|${i}`))) })] }));
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* 外观指纹:去掉身份与 Joplo 锚点属性(id、data-j*、aria-*)后的标记。同一个 motion 键前后指纹不同(换了 class、
|
|
432
|
+
* 内联样式、内部结构或文字)时,旧样子要跟着飞并淡出,不能只插值键元素自己的几个样式(内层的底色、斜面边框会跳变)。
|
|
433
|
+
*/
|
|
434
|
+
export function lookKey(el) {
|
|
435
|
+
const c = el.cloneNode(true);
|
|
436
|
+
// 退场幽灵插在原父元素里,可能就在这个键元素内部:不算它的外观
|
|
437
|
+
for (const g of c.querySelectorAll('[data-jghost]'))
|
|
438
|
+
g.remove();
|
|
439
|
+
for (const n of [c, ...c.querySelectorAll('*')])
|
|
440
|
+
for (const a of [...n.getAttributeNames()])
|
|
441
|
+
if (a === 'id' || a.startsWith('data-j') || a.startsWith('aria-') || a === 'tabindex' || a === 'inert')
|
|
442
|
+
n.removeAttribute(a);
|
|
443
|
+
return c.outerHTML;
|
|
444
|
+
}
|
|
275
445
|
/** One observer per stage: cache only design-space layouts, never player state. */
|
|
276
446
|
export const observe = (root, initial) => {
|
|
277
447
|
const context0Inputs = initial?.frame.inputs;
|
|
@@ -333,10 +503,11 @@ export const observe = (root, initial) => {
|
|
|
333
503
|
a.cancel();
|
|
334
504
|
}
|
|
335
505
|
};
|
|
336
|
-
const ghostOf = (el, removed, parent, next, world) => {
|
|
506
|
+
const ghostOf = (el, removed, parent, next, world, ranks) => {
|
|
337
507
|
const box = exitBoxes.get(world)?.get(el);
|
|
338
508
|
const kind = el.dataset.jpContentExit ?? '';
|
|
339
|
-
|
|
509
|
+
const away = AWAY[kind];
|
|
510
|
+
if (!box || !away || typeof el.animate !== 'function')
|
|
340
511
|
return;
|
|
341
512
|
// 同一个 motion 键在新画面里还在:交给 FLIP(以变形为准,不叠加退场)
|
|
342
513
|
const key = el.dataset.jpContentMotion;
|
|
@@ -375,7 +546,14 @@ export const observe = (root, initial) => {
|
|
|
375
546
|
}
|
|
376
547
|
put('left', `${box.x - origin.x}px`);
|
|
377
548
|
put('top', `${box.y - origin.y}px`);
|
|
378
|
-
|
|
549
|
+
// 错峰的容器:先在一起被移除的子树里找,再从仍在页面上的父元素往上找
|
|
550
|
+
let host = null;
|
|
551
|
+
for (let a = el === removed ? null : el.parentElement; a && !host; a = a === removed ? null : a.parentElement)
|
|
552
|
+
if (a.hasAttribute('data-jp-content-exit-stagger'))
|
|
553
|
+
host = a;
|
|
554
|
+
host ??= parent.closest('[data-jp-content-exit-stagger]');
|
|
555
|
+
const delay = msOf(el.dataset.jpContentExitDelay, 0) + staggered(ranks, host, 'exitStagger');
|
|
556
|
+
const anim = ghost.animate(transitionFrames(away, false), { duration: msOf(el.dataset.jpContentExitMs, EXIT_MS), delay, easing: easeOf(el.dataset.jpContentExitEase, EXIT_EASE), fill: 'forwards' });
|
|
379
557
|
anim.id = 'jexit';
|
|
380
558
|
ghosts.set(outer, anim);
|
|
381
559
|
const done = () => { if (ghosts.get(outer) === anim)
|
|
@@ -384,6 +562,7 @@ export const observe = (root, initial) => {
|
|
|
384
562
|
anim.addEventListener('cancel', done, { once: true });
|
|
385
563
|
};
|
|
386
564
|
const handle = (records, world) => {
|
|
565
|
+
const ranks = new Map();
|
|
387
566
|
for (const r of records)
|
|
388
567
|
for (const n of r.removedNodes) {
|
|
389
568
|
if (!(n instanceof HTMLElement) || n.isConnected || ghosts.has(n) || n.hasAttribute('data-jghost') || quiet)
|
|
@@ -397,7 +576,7 @@ export const observe = (root, initial) => {
|
|
|
397
576
|
break;
|
|
398
577
|
}
|
|
399
578
|
if (outermost)
|
|
400
|
-
ghostOf(el, n, r.target, r.nextSibling, world);
|
|
579
|
+
ghostOf(el, n, r.target, r.nextSibling, world, ranks);
|
|
401
580
|
}
|
|
402
581
|
}
|
|
403
582
|
};
|
|
@@ -468,7 +647,11 @@ export const observe = (root, initial) => {
|
|
|
468
647
|
if (!r)
|
|
469
648
|
continue;
|
|
470
649
|
const prev = previous.get(key);
|
|
471
|
-
|
|
650
|
+
const style = subjectStyle(el), text = el.textContent ?? '', look = lookKey(el);
|
|
651
|
+
const shells = [];
|
|
652
|
+
for (let p = el.parentElement; p && p !== w; p = p.parentElement)
|
|
653
|
+
shells.push(p.cloneNode(false));
|
|
654
|
+
seen.set(key, { ...r, style, text, look, clone: el.cloneNode(true), shells });
|
|
472
655
|
if (!context.frame.animate) {
|
|
473
656
|
for (const a of el.getAnimations?.() ?? [])
|
|
474
657
|
if (a.id === 'jmotion')
|
|
@@ -482,7 +665,10 @@ export const observe = (root, initial) => {
|
|
|
482
665
|
a.cancel();
|
|
483
666
|
continue;
|
|
484
667
|
}
|
|
485
|
-
|
|
668
|
+
const styleChanged = prev.style && Object.keys(style).some(k => prev.style[k] !== style[k]);
|
|
669
|
+
// 文字变了,或外观指纹变了(同键换成另一个样子:纯文字 → 彩色块、1984 的按钮 → 1995 的按钮):旧样子交叉淡出
|
|
670
|
+
const textChanged = prev.text !== undefined && prev.text !== text || prev.look !== undefined && prev.look !== look;
|
|
671
|
+
if (!styleChanged && !textChanged && Math.abs(prev.x - r.x) < 0.5 && Math.abs(prev.y - r.y) < 0.5 && Math.abs(prev.w - r.w) < 0.5 && Math.abs(prev.h - r.h) < 0.5)
|
|
486
672
|
continue;
|
|
487
673
|
const dx = prev.x + prev.w / 2 - (r.x + r.w / 2);
|
|
488
674
|
const dy = prev.y + prev.h / 2 - (r.y + r.h / 2);
|
|
@@ -493,13 +679,35 @@ export const observe = (root, initial) => {
|
|
|
493
679
|
a.cancel();
|
|
494
680
|
if (typeof el.animate !== 'function')
|
|
495
681
|
continue;
|
|
496
|
-
const anim = el.animate([{ translate: `${dx}px ${dy}px`, scale: `${sx} ${sy}` }, { translate: '0px 0px', scale: '1 1' }], { duration: el.dataset.jpContentMotionMs === undefined ? flight.ms : Number(el.dataset.jpContentMotionMs), easing: flight.ease, delay: Number(el.dataset.jpContentMotionDelay) || 0, fill: 'backwards' });
|
|
682
|
+
const anim = el.animate([{ ...prev.style, ...(textChanged ? { opacity: 0 } : {}), translate: `${dx}px ${dy}px`, scale: `${sx} ${sy}` }, { ...style, translate: '0px 0px', scale: '1 1' }], { duration: el.dataset.jpContentMotionMs === undefined ? flight.ms : Number(el.dataset.jpContentMotionMs), easing: easeOf(el.dataset.jpContentMotionEase, flight.ease), delay: Number(el.dataset.jpContentMotionDelay) || 0, fill: 'backwards' });
|
|
683
|
+
if (textChanged && prev.clone) {
|
|
684
|
+
const ghost = prev.clone.cloneNode(true);
|
|
685
|
+
let outer = ghost;
|
|
686
|
+
for (const parent of prev.shells ?? []) {
|
|
687
|
+
const shell = parent.cloneNode(false);
|
|
688
|
+
shell.style.setProperty('display', 'contents', 'important');
|
|
689
|
+
shell.append(outer);
|
|
690
|
+
outer = shell;
|
|
691
|
+
}
|
|
692
|
+
strip(outer);
|
|
693
|
+
outer.setAttribute('aria-hidden', 'true');
|
|
694
|
+
outer.setAttribute('inert', '');
|
|
695
|
+
outer.dataset.jghost = '';
|
|
696
|
+
Object.assign(ghost.style, { position: 'absolute', left: `${r.x}px`, top: `${r.y}px`, width: `${r.w}px`, height: `${r.h}px`, margin: '0', pointerEvents: 'none', ...prev.style });
|
|
697
|
+
w.appendChild(outer);
|
|
698
|
+
const fade = ghost.animate([{ opacity: prev.style?.opacity ?? '1', translate: `${dx}px ${dy}px`, scale: `${sx} ${sy}` }, { opacity: 0, translate: '0px 0px', scale: '1 1' }], { duration: el.dataset.jpContentMotionMs === undefined ? flight.ms : Number(el.dataset.jpContentMotionMs), easing: easeOf(el.dataset.jpContentMotionEase, flight.ease), delay: Number(el.dataset.jpContentMotionDelay) || 0, fill: 'both' });
|
|
699
|
+
ghosts.set(outer, fade);
|
|
700
|
+
fade.addEventListener('finish', () => drop(outer), { once: true });
|
|
701
|
+
fade.addEventListener('cancel', () => drop(outer), { once: true });
|
|
702
|
+
}
|
|
497
703
|
anim.id = 'jmotion';
|
|
498
704
|
flights.set(anim, { el, world: w, effect: anim.effect, release: lift(el, w) });
|
|
499
705
|
anim.addEventListener('finish', () => forget(anim), { once: true });
|
|
500
706
|
anim.addEventListener('cancel', () => forget(anim), { once: true });
|
|
501
707
|
}
|
|
502
708
|
// 3) 进场:第一次出现的元素(新的 DOM 节点)。画布刚出现、安静的提交、FLIP 接管的同键元素都不播
|
|
709
|
+
// 错峰按文档顺序数:同一个 enterStagger 容器里这次真正播进场的第 n 个,多等 n × stagger
|
|
710
|
+
const ranks = new Map();
|
|
503
711
|
for (const el of w.querySelectorAll('[data-jp-content-enter]')) {
|
|
504
712
|
if (present.has(el))
|
|
505
713
|
continue;
|
|
@@ -510,7 +718,8 @@ export const observe = (root, initial) => {
|
|
|
510
718
|
const key = el.dataset.jpContentMotion;
|
|
511
719
|
if (key && previous.has(key))
|
|
512
720
|
continue;
|
|
513
|
-
const
|
|
721
|
+
const delay = msOf(el.dataset.jpContentEnterDelay, 0) + staggered(ranks, el.parentElement?.closest('[data-jp-content-enter-stagger]') ?? null, 'enterStagger');
|
|
722
|
+
const anim = el.animate(transitionFrames(AWAY[kind], true), { duration: msOf(el.dataset.jpContentEnterMs, ENTER_MS), delay, easing: easeOf(el.dataset.jpContentEnterEase, ENTER_EASE), fill: 'backwards' });
|
|
514
723
|
anim.id = 'jenter';
|
|
515
724
|
entering.add(anim);
|
|
516
725
|
anim.addEventListener('finish', () => entering.delete(anim), { once: true });
|
|
@@ -546,4 +755,4 @@ export const observe = (root, initial) => {
|
|
|
546
755
|
},
|
|
547
756
|
};
|
|
548
757
|
};
|
|
549
|
-
export default defineRuntime({ id: 'content', observe, components: { Canvas: { react: Canvas } } });
|
|
758
|
+
export default defineRuntime({ id: 'content', observe, components: { Canvas: { react: Canvas }, Split: { react: Split } } });
|
package/dist/version.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joplo-app/plugin-content",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"joplo": {
|
|
6
6
|
"api": 2
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"zod": "4.6.7",
|
|
25
|
-
"@joplo-app/kit": "0.
|
|
25
|
+
"@joplo-app/kit": "0.7.1",
|
|
26
26
|
"react": "19.3.1"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|