@dxtmisha/wiki 0.39.8 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/{defineProperty-Bjg6wMoX.js → defineProperty-149Ahniv.js} +4 -4
  2. package/dist/library.js +1 -1
  3. package/dist/media/descriptions/wikiDescriptionsArea.d.ts +7 -0
  4. package/dist/media/descriptions/wikiDescriptionsClientOnly.d.ts +7 -0
  5. package/dist/media/descriptions/wikiDescriptionsContainer.d.ts +7 -0
  6. package/dist/media/descriptions/wikiDescriptionsHeader.d.ts +7 -0
  7. package/dist/media/descriptions/wikiDescriptionsPageArea.d.ts +7 -0
  8. package/dist/media/mdx/Area/wikiMdxArea.d.ts +7 -0
  9. package/dist/media/mdx/ClientOnly/wikiMdxClientOnly.d.ts +7 -0
  10. package/dist/media/mdx/Container/wikiMdxContainer.d.ts +7 -0
  11. package/dist/media/mdx/Header/wikiMdxHeader.d.ts +7 -0
  12. package/dist/media/mdx/PageArea/wikiMdxPageArea.d.ts +7 -0
  13. package/dist/media.d.ts +1 -1
  14. package/dist/media.js +115 -68
  15. package/dist/storybook.js +2707 -1841
  16. package/dist/{wikiDescriptions-Cv4WzSNL.js → wikiDescriptions-7XaHU3Yk.js} +182 -0
  17. package/package.json +1 -1
  18. package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.en.mdx +43 -0
  19. package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.ru.mdx +43 -0
  20. package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.vi.mdx +41 -0
  21. package/src/media/functional/functional/composables/useApiRef/useApiRef.en.mdx +20 -4
  22. package/src/media/functional/functional/composables/useApiRef/useApiRef.ru.mdx +21 -3
  23. package/src/media/functional/functional/composables/useApiRef/useApiRef.vi.mdx +20 -2
  24. package/src/media/functional/functional/functions/computedAsync/computedAsync.en.mdx +8 -0
  25. package/src/media/functional/functional/functions/computedAsync/computedAsync.ru.mdx +8 -0
  26. package/src/media/functional/functional/functions/computedAsync/computedAsync.vi.mdx +8 -0
  27. package/src/media/functional/functional/functions/computedEternity/computedEternity.en.mdx +8 -0
  28. package/src/media/functional/functional/functions/computedEternity/computedEternity.ru.mdx +8 -0
  29. package/src/media/functional/functional/functions/computedEternity/computedEternity.vi.mdx +8 -0
  30. package/src/media/functional/functional-basic/classes/Api/Api.en.mdx +3 -0
  31. package/src/media/functional/functional-basic/classes/Api/Api.ru.mdx +3 -0
  32. package/src/media/functional/functional-basic/classes/Api/Api.vi.mdx +3 -0
  33. package/src/media/functional/functional-basic/classes/ApiInstance/ApiInstance.en.mdx +5 -2
  34. package/src/media/functional/functional-basic/classes/ApiInstance/ApiInstance.ru.mdx +6 -3
  35. package/src/media/functional/functional-basic/classes/ApiInstance/ApiInstance.vi.mdx +5 -2
  36. package/src/media/functional/functional-basic/classes/ApiResponse/ApiResponse.en.mdx +9 -0
  37. package/src/media/functional/functional-basic/classes/ApiResponse/ApiResponse.ru.mdx +9 -0
  38. package/src/media/functional/functional-basic/classes/ApiResponse/ApiResponse.vi.mdx +9 -0
  39. package/src/media/functional/functional-basic/classes/CookieStorage/CookieStorage.en.mdx +31 -6
  40. package/src/media/functional/functional-basic/classes/CookieStorage/CookieStorage.ru.mdx +31 -6
  41. package/src/media/functional/functional-basic/classes/CookieStorage/CookieStorage.vi.mdx +31 -6
  42. package/src/media/functional/functional-basic/classes/Meta/Meta.en.mdx +16 -0
  43. package/src/media/functional/functional-basic/classes/Meta/Meta.ru.mdx +16 -0
  44. package/src/media/functional/functional-basic/classes/Meta/Meta.vi.mdx +17 -1
  45. package/src/media/functional/functional-basic/classes/MetaManager/MetaManager.en.mdx +9 -0
  46. package/src/media/functional/functional-basic/classes/MetaManager/MetaManager.ru.mdx +9 -0
  47. package/src/media/functional/functional-basic/classes/MetaManager/MetaManager.vi.mdx +9 -0
  48. package/src/media/functional/functional-basic/classes/MetaStatic/MetaStatic.en.mdx +2 -1
  49. package/src/media/functional/functional-basic/classes/MetaStatic/MetaStatic.ru.mdx +2 -1
  50. package/src/media/functional/functional-basic/classes/MetaStatic/MetaStatic.vi.mdx +3 -2
  51. package/src/media/functional/functional-basic/classes/ServerStorage/ServerStorage.en.mdx +2 -2
  52. package/src/media/functional/functional-basic/classes/ServerStorage/ServerStorage.ru.mdx +2 -2
  53. package/src/media/functional/functional-basic/classes/ServerStorage/ServerStorage.vi.mdx +2 -2
  54. package/src/media/functional/functional-basic/icons/icons.en.mdx +3 -0
  55. package/src/media/functional/functional-basic/icons/icons.ru.mdx +3 -0
  56. package/src/media/functional/functional-basic/icons/icons.vi.mdx +3 -0
  57. package/src/media/functional/nitro-basic/about/about.en.mdx +52 -0
  58. package/src/media/functional/nitro-basic/about/about.ru.mdx +52 -0
  59. package/src/media/functional/nitro-basic/about/about.vi.mdx +52 -0
  60. package/src/media/functional/nitro-basic/composables/useHeaders/useHeaders.en.mdx +29 -0
  61. package/src/media/functional/nitro-basic/composables/useHeaders/useHeaders.ru.mdx +29 -0
  62. package/src/media/functional/nitro-basic/composables/useHeaders/useHeaders.vi.mdx +29 -0
  63. package/src/media/functional/nitro-basic/functions/getRequestOrigin/getRequestOrigin.en.mdx +24 -0
  64. package/src/media/functional/nitro-basic/functions/getRequestOrigin/getRequestOrigin.ru.mdx +24 -0
  65. package/src/media/functional/nitro-basic/functions/getRequestOrigin/getRequestOrigin.vi.mdx +24 -0
  66. package/src/media/functional/nitro-basic/functions/getRequestUrl/getRequestUrl.en.mdx +24 -0
  67. package/src/media/functional/nitro-basic/functions/getRequestUrl/getRequestUrl.ru.mdx +24 -0
  68. package/src/media/functional/nitro-basic/functions/getRequestUrl/getRequestUrl.vi.mdx +24 -0
  69. package/src/media/functional/nitro-basic/functions/initApi/initApi.en.mdx +23 -0
  70. package/src/media/functional/nitro-basic/functions/initApi/initApi.ru.mdx +23 -0
  71. package/src/media/functional/nitro-basic/functions/initApi/initApi.vi.mdx +23 -0
  72. package/src/media/functional/nitro-basic/functions/initClientRouter/initClientRouter.en.mdx +21 -0
  73. package/src/media/functional/nitro-basic/functions/initClientRouter/initClientRouter.ru.mdx +21 -0
  74. package/src/media/functional/nitro-basic/functions/initClientRouter/initClientRouter.vi.mdx +21 -0
  75. package/src/media/functional/nitro-basic/functions/initCookieStorage/initCookieStorage.en.mdx +18 -0
  76. package/src/media/functional/nitro-basic/functions/initCookieStorage/initCookieStorage.ru.mdx +18 -0
  77. package/src/media/functional/nitro-basic/functions/initCookieStorage/initCookieStorage.vi.mdx +18 -0
  78. package/src/media/functional/nitro-basic/functions/initHeaders/initHeaders.en.mdx +16 -0
  79. package/src/media/functional/nitro-basic/functions/initHeaders/initHeaders.ru.mdx +16 -0
  80. package/src/media/functional/nitro-basic/functions/initHeaders/initHeaders.vi.mdx +16 -0
  81. package/src/media/functional/nitro-basic/functions/initPluginApiCache/initPluginApiCache.en.mdx +17 -0
  82. package/src/media/functional/nitro-basic/functions/initPluginApiCache/initPluginApiCache.ru.mdx +17 -0
  83. package/src/media/functional/nitro-basic/functions/initPluginApiCache/initPluginApiCache.vi.mdx +17 -0
  84. package/src/media/functional/nitro-basic/functions/initPluginBasic/initPluginBasic.en.mdx +34 -0
  85. package/src/media/functional/nitro-basic/functions/initPluginBasic/initPluginBasic.ru.mdx +34 -0
  86. package/src/media/functional/nitro-basic/functions/initPluginBasic/initPluginBasic.vi.mdx +34 -0
  87. package/src/media/functional/nitro-basic/functions/initScriptsJson/initScriptsJson.en.mdx +17 -0
  88. package/src/media/functional/nitro-basic/functions/initScriptsJson/initScriptsJson.ru.mdx +17 -0
  89. package/src/media/functional/nitro-basic/functions/initScriptsJson/initScriptsJson.vi.mdx +17 -0
  90. package/src/media/functional/nitro-basic/functions/initServerRouter/initServerRouter.en.mdx +20 -0
  91. package/src/media/functional/nitro-basic/functions/initServerRouter/initServerRouter.ru.mdx +20 -0
  92. package/src/media/functional/nitro-basic/functions/initServerRouter/initServerRouter.vi.mdx +20 -0
  93. package/src/media/functional/nitro-basic/functions/initServerStorage/initServerStorage.en.mdx +16 -0
  94. package/src/media/functional/nitro-basic/functions/initServerStorage/initServerStorage.ru.mdx +16 -0
  95. package/src/media/functional/nitro-basic/functions/initServerStorage/initServerStorage.vi.mdx +16 -0
  96. package/src/media/functional/nitro-basic/functions/initSsrApp/initSsrApp.en.mdx +20 -0
  97. package/src/media/functional/nitro-basic/functions/initSsrApp/initSsrApp.ru.mdx +20 -0
  98. package/src/media/functional/nitro-basic/functions/initSsrApp/initSsrApp.vi.mdx +20 -0
  99. package/src/media/functional/nitro-basic/functions/uiBootstrapClient/uiBootstrapClient.en.mdx +14 -0
  100. package/src/media/functional/nitro-basic/functions/uiBootstrapClient/uiBootstrapClient.ru.mdx +14 -0
  101. package/src/media/functional/nitro-basic/functions/uiBootstrapClient/uiBootstrapClient.vi.mdx +14 -0
  102. package/src/media/functional/nitro-basic/functions/uiBootstrapServer/uiBootstrapServer.en.mdx +19 -0
  103. package/src/media/functional/nitro-basic/functions/uiBootstrapServer/uiBootstrapServer.ru.mdx +19 -0
  104. package/src/media/functional/nitro-basic/functions/uiBootstrapServer/uiBootstrapServer.vi.mdx +19 -0
  105. package/src/media/functional/nitro-basic/functions/uiCookieStorage/uiCookieStorage.en.mdx +13 -0
  106. package/src/media/functional/nitro-basic/functions/uiCookieStorage/uiCookieStorage.ru.mdx +13 -0
  107. package/src/media/functional/nitro-basic/functions/uiCookieStorage/uiCookieStorage.vi.mdx +13 -0
  108. package/src/media/functional/nitro-basic/functions/uiCreateApp/uiCreateApp.en.mdx +43 -0
  109. package/src/media/functional/nitro-basic/functions/uiCreateApp/uiCreateApp.ru.mdx +43 -0
  110. package/src/media/functional/nitro-basic/functions/uiCreateApp/uiCreateApp.vi.mdx +43 -0
  111. package/src/media/functional/nitro-basic/functions/uiCreateClientApp/uiCreateClientApp.en.mdx +31 -0
  112. package/src/media/functional/nitro-basic/functions/uiCreateClientApp/uiCreateClientApp.ru.mdx +31 -0
  113. package/src/media/functional/nitro-basic/functions/uiCreateClientApp/uiCreateClientApp.vi.mdx +31 -0
  114. package/src/media/functional/nitro-basic/functions/uiCreateServerApp/uiCreateServerApp.en.mdx +34 -0
  115. package/src/media/functional/nitro-basic/functions/uiCreateServerApp/uiCreateServerApp.ru.mdx +34 -0
  116. package/src/media/functional/nitro-basic/functions/uiCreateServerApp/uiCreateServerApp.vi.mdx +34 -0
  117. package/src/media/functional/nitro-basic/functions/uiCreateSsrRouter/uiCreateSsrRouter.en.mdx +17 -0
  118. package/src/media/functional/nitro-basic/functions/uiCreateSsrRouter/uiCreateSsrRouter.ru.mdx +17 -0
  119. package/src/media/functional/nitro-basic/functions/uiCreateSsrRouter/uiCreateSsrRouter.vi.mdx +17 -0
  120. package/src/media/functional/nitro-basic/functions/uiId/uiId.en.mdx +13 -0
  121. package/src/media/functional/nitro-basic/functions/uiId/uiId.ru.mdx +13 -0
  122. package/src/media/functional/nitro-basic/functions/uiId/uiId.vi.mdx +13 -0
  123. package/src/media/functional/nitro-basic/functions/uiServerStorage/uiServerStorage.en.mdx +13 -0
  124. package/src/media/functional/nitro-basic/functions/uiServerStorage/uiServerStorage.ru.mdx +13 -0
  125. package/src/media/functional/nitro-basic/functions/uiServerStorage/uiServerStorage.vi.mdx +13 -0
  126. package/src/media/functional/nitro-basic/setup/setup.en.mdx +133 -0
  127. package/src/media/functional/nitro-basic/setup/setup.ru.mdx +133 -0
  128. package/src/media/functional/nitro-basic/setup/setup.vi.mdx +133 -0
@@ -58,6 +58,35 @@ var e = [
58
58
  description: "\nCollapsible container for progressive disclosure. Toggles content visibility to manage space and cognitive load. Use for FAQs, grouped settings, hiding secondary info, or compact dashboards.\nHeader is based on a Cell component and supports label, description, and icon. Features an auto-rotating arrow indicator and smooth height transitions via MotionTransform.\nBuilt-in ARIA support and keyboard navigation (Space/Enter). Controlled primarily via v-model:open. Customizable with divider and header attributes through cellAttrs.\n "
59
59
  }
60
60
  },
61
+ {
62
+ name: "Area",
63
+ description: {
64
+ en: "Component for rendering content based on the current area context",
65
+ ru: "Компонент для отображения контента в зависимости от текущего контекста области"
66
+ },
67
+ possibilities: {
68
+ en: [
69
+ "automatic slot selection based on injected area value",
70
+ "fallback to a default area if no injection is found",
71
+ "supports nested areas and context inheritance",
72
+ "renders default slot if no specific area slot matches"
73
+ ],
74
+ ru: [
75
+ "автоматический выбор слота на основе внедренного значения области",
76
+ "возврат к области по умолчанию, если внедрение не найдено",
77
+ "поддержка вложенных областей и наследования контекста",
78
+ "отображение слота по умолчанию, если ни один специфический слот области не подходит"
79
+ ]
80
+ },
81
+ import: [],
82
+ render: "\n <DesignComponent v-bind=\"args\">\n <template #header>Header Content (from area-default)</template>\n <template #footer>Footer Content</template>\n <template #default>Default Content</template>\n </DesignComponent>\n ",
83
+ stories: [],
84
+ documentation: {
85
+ body: "\n<StorybookDescriptions componentName={'Area'} type={'area'}/>\n ",
86
+ slots: "\n<StorybookDescriptions componentName={'Area'} type={'slot'}/>\n "
87
+ },
88
+ ai: { description: "\nA utility component that acts as a dynamic slot switcher based on an \"area\" context.\nIt retrieves the current area value from the injection context (UI_AREA_VALUE) or uses the 'areaDefault' prop.\nIt then renders the slot that matches the area name. If no matching slot is found, it falls back to the 'default' slot.\nThis is particularly useful for building layouts where different components need to render different content depending on where they are placed (e.g., in a header, footer, or side panel).\n " }
89
+ },
61
90
  {
62
91
  name: "Actions",
63
92
  description: {
@@ -748,6 +777,70 @@ var e = [
748
777
  },
749
778
  ai: { description: "\nWrapper component for managing collections of Chip elements based on an array of data. Streamlines the creation of filter sets, choice groups, and tag lists by automating iteration and selection logic.\nFeatures support for single and multiple selection modes, shared chip attributes (via chipAttrs), and icon visibility control. Includes built-in data binding for selected values and @click event propagation.\nControlled via the list prop for data and v-model:selected for state. Use for dynamic filtering interfaces, selecting multiple categories, or building interactive tag lists from API data.\n " }
750
779
  },
780
+ {
781
+ name: "ClientOnly",
782
+ description: {
783
+ en: "Component for managing rendering exclusively on the client side, essential for SSR compatibility",
784
+ ru: "Компонент для управления рендерингом исключительно на стороне клиента, необходим для совместимости с SSR"
785
+ },
786
+ possibilities: {
787
+ en: [
788
+ "prevents hydration mismatch errors in SSR/SSG environments",
789
+ "render client-side only components (e.g. charts, maps)",
790
+ "toggleable via \"clientOnly\" property",
791
+ "supports default slot for the content"
792
+ ],
793
+ ru: [
794
+ "предотвращает ошибки рассогласования гидратации в средах SSR/SSG",
795
+ "рендерит компоненты только для клиента (например, графики, карты)",
796
+ "переключается через свойство \"clientOnly\"",
797
+ "поддерживает слот default для контента"
798
+ ]
799
+ },
800
+ import: [],
801
+ render: "\n <DesignComponent>\n <h4>Client-Side Content</h4>\n <p>This block is only visible when the component is mounted in the browser.</p>\n <p>Use it for components that depend on window, document, or other browser-specific APIs.</p>\n </DesignComponent>\n ",
802
+ stories: [],
803
+ documentation: {
804
+ body: "\n<StorybookDescriptions componentName={'ClientOnly'} type={'clientOnly'}/>\n ",
805
+ slots: "\n<StorybookDescriptions componentName={'Slot'} type={'default'}/>\n "
806
+ },
807
+ ai: {
808
+ render: "\n<div :class=\"classDemo.item\">\n <ClientOnly v-bind=\"args\">\n <h4>Client-Side Content</h4>\n <p>This block is only visible when the component is mounted in the browser.</p>\n <p>Use it for components that depend on window, document, or other browser-specific APIs.</p>\n </ClientOnly>\n</div>\n ",
809
+ description: "\nThe ClientOnly component is a utility designed to ensure that its children are only rendered on the client side.\nThis is particularly useful in Server-Side Rendering (SSR) or Static Site Generation (SSG) contexts where certain components\n(like those relying on browser-only APIs like 'window' or 'document', or complex visualizations) should not be executed or rendered on the server.\nIt works by waiting until the component is mounted in the browser before rendering its content.\nControlled by the 'clientOnly' boolean property (default is true).\n "
810
+ }
811
+ },
812
+ {
813
+ name: "Container",
814
+ description: {
815
+ en: "A lightweight layout container for centering and constraining content width with configurable horizontal alignment.",
816
+ ru: "Легковесный компонент-контейнер для центрирования и ограничения ширины контента с настраиваемым горизонтальным выравниванием."
817
+ },
818
+ possibilities: {
819
+ en: [
820
+ "horizontal alignment with align: left | center | right",
821
+ "configurable width and horizontal margins via design tokens",
822
+ "default slot for wrapping arbitrary content",
823
+ "area context support through the area prop"
824
+ ],
825
+ ru: [
826
+ "горизонтальное выравнивание через align: left | center | right",
827
+ "настройка ширины и горизонтальных отступов через дизайн-токены",
828
+ "слот default для оборачивания произвольного контента",
829
+ "поддержка контекста области через свойство area"
830
+ ]
831
+ },
832
+ import: [],
833
+ render: "\n <DesignComponent v-bind=\"args\">\n <p>\n Container helps keep content readable by limiting line length and controlling side spacing.\n </p>\n <p>\n Use it as a base layout wrapper for page sections, forms, and content blocks.\n </p>\n </DesignComponent>\n ",
834
+ stories: [],
835
+ documentation: {
836
+ body: "\n<StorybookDescriptions componentName={'Container'} type={'container'}/>\n ",
837
+ slots: "\n<StorybookDescriptions componentName={'Slot'} type={'default'}/>\n "
838
+ },
839
+ ai: {
840
+ render: "\n<div :class=\"classDemo.item\">\n <Container v-bind=\"args\">\n Main content goes here.\n </Container>\n</div>\n ",
841
+ description: "\nLayout wrapper used to constrain content width and manage horizontal spacing in a predictable way.\nSupports alignment options (left, center, right), width tokens, and side margins so page content keeps consistent rhythm across breakpoints.\nUse as a foundational container around sections, forms, and text-heavy blocks to improve readability and layout consistency.\n "
842
+ }
843
+ },
751
844
  {
752
845
  name: "Dialog",
753
846
  description: {
@@ -1143,6 +1236,52 @@ var e = [
1143
1236
  description: "\nStructural component for organizing related content with a standardized header hierarchy. Acts as a semantic wrapper for subsections or grouping elements within a larger section or card.\nFeatures support for headlines (h4 by default), labels, icons, and descriptions. Inherits all capabilities of the Block component, providing a consistent layout for titles and body content.\nControlled via headline, label, and description props. Use for grouping settings, categorizing information, or breaking down complex forms into logical, titled segments.\n "
1144
1237
  }
1145
1238
  },
1239
+ {
1240
+ name: "Header",
1241
+ description: {
1242
+ en: "Component for displaying headers with icons and additional information",
1243
+ ru: "Компонент для отображения заголовков с иконками и дополнительной информацией"
1244
+ },
1245
+ possibilities: {
1246
+ en: [
1247
+ "support for different HTML tags (h1-h6, div, etc.)",
1248
+ "built-in support for icons and captions",
1249
+ "customizable trailing content via slots",
1250
+ "automatic area value management",
1251
+ "standardized typography and spacing"
1252
+ ],
1253
+ ru: [
1254
+ "поддержка различных HTML-тегов (h1-h6, div и т.д.)",
1255
+ "встроенная поддержка иконок и подписей",
1256
+ "настраиваемый правый контент через слоты",
1257
+ "автоматическое управление значением области",
1258
+ "стандартизированная типографика и отступы"
1259
+ ]
1260
+ },
1261
+ import: [],
1262
+ stories: [{
1263
+ id: "HeaderBasic",
1264
+ name: {
1265
+ en: "Basic",
1266
+ ru: "Базовые"
1267
+ },
1268
+ template: "\n <div class=\"wiki-storybook-flex--column\">\n <DesignComponent label=\"Header Level 1\" tag=\"h1\" />\n <DesignComponent label=\"Header Level 2\" tag=\"h2\" />\n <DesignComponent label=\"Header Level 3\" tag=\"h3\" />\n </div>\n "
1269
+ }, {
1270
+ id: "HeaderSlots",
1271
+ name: {
1272
+ en: "Slots",
1273
+ ru: "Слоты"
1274
+ },
1275
+ template: "\n <DesignComponent label=\"Default label\" caption=\"Default caption\">\n <template #default>Custom label slot</template>\n <template #caption>Custom caption slot</template>\n <template #trailing>Trailing slot</template>\n </DesignComponent>\n "
1276
+ }],
1277
+ documentation: {
1278
+ body: "\n<StorybookDescriptions componentName={'Header'} type={'header'}/>\n<Canvas of={Component.HeaderBasic}/>\n ",
1279
+ events: "",
1280
+ expose: "",
1281
+ slots: "\n<Canvas of={Component.HeaderSlots}/>\n<StorybookDescriptions componentName={'Slot'} type={'default'}/>\n<StorybookDescriptions componentName={'Slot'} type={'caption'}/>\n<StorybookDescriptions componentName={'Slot'} type={'trailing'}/>\n "
1282
+ },
1283
+ ai: { description: "\nComponent for creating structured headers with integrated support for icons and captions.\nAllows flexible control over the HTML tag (h1-h6, div) to maintain proper document hierarchy.\nIncludes automatic area management and support for custom trailing content.\nIdeal for section titles, page headers, or grouped content labeling.\n " }
1284
+ },
1146
1285
  {
1147
1286
  name: "HorizontalScroll",
1148
1287
  description: {
@@ -2029,6 +2168,49 @@ var e = [
2029
2168
  description: "\nTop-level structural container designed to wrap the primary content of a view or document. Serves as a semantic root (typically rendering a <main> tag) and establishes the high-level document hierarchy with standardized headers.\nFeatures a comprehensive header structure inherited from the Block component, including support for headlines (h1), labels (page titles), descriptions, and trailing action areas. Automatically manages spacing and layout consistency for page-level navigation and identity.\nControlled via headline, label, and icon props, with dedicated slots for content and actions (#default, #trailing). Use as the foundational wrapper for any route or unique screen to ensure accessibility and consistent information architecture.\n "
2030
2169
  }
2031
2170
  },
2171
+ {
2172
+ name: "PageArea",
2173
+ description: {
2174
+ en: "A structural component that automatically selects and renders appropriate UI blocks (Page, Section, Block, or Group) based on the current nesting level or area context.",
2175
+ ru: "Структурный компонент, который автоматически выбирает и отрисовывает подходящие блоки интерфейса (Page, Section, Block или Group) в зависимости от текущего уровня вложенности или контекста области."
2176
+ },
2177
+ possibilities: {
2178
+ en: [
2179
+ "automatic component switching based on area context",
2180
+ "semantic content organization with consistent structure",
2181
+ "integration with layout zones and hierarchical state",
2182
+ "shorthand for complex page layouts with nested elements"
2183
+ ],
2184
+ ru: [
2185
+ "автоматическое переключение компонентов на основе контекста области",
2186
+ "семантическая организация контента с согласованной структурой",
2187
+ "интеграция с зонами макета и иерархическим состоянием",
2188
+ "сокращенная запись для сложных макетов страниц с вложенными элементами"
2189
+ ]
2190
+ },
2191
+ import: [],
2192
+ render: "\n <DesignComponent v-bind=\"args\">\n <p>\n The PageArea component is a specialized container designed to structure the content within a specific page or layout region.\n It provides consistent margins, alignment, and semantic grouping for nested components.\n </p>\n <p>\n It acts as an orchestrator for various UI blocks, allowing developers to define a clear information hierarchy.\n Whether it's a dashboard overview or a detailed data view, PageArea ensures the layout remains cohesive.\n </p>\n </DesignComponent>\n ",
2193
+ stories: [{
2194
+ id: "PageAreaBasic",
2195
+ name: {
2196
+ en: "Basic",
2197
+ ru: "Базовые"
2198
+ },
2199
+ template: "\n <DesignComponent>\n <p>This is a basic example of PageArea content. It can contain any combination of blocks, sections, or individual UI elements.</p>\n </DesignComponent>\n "
2200
+ }, {
2201
+ id: "PageAreaSlots",
2202
+ name: {
2203
+ en: "Slots usage",
2204
+ ru: "Использование слотов"
2205
+ },
2206
+ template: "\n <DesignComponent>\n <template #default>Default slot</template>\n <template #headline>Headline slot</template>\n <template #label>Label slot</template>\n <template #description>Description slot</template>\n <template #caption>Caption slot</template>\n <template #trailing>Trailing slot</template>\n </DesignComponent>\n "
2207
+ }],
2208
+ documentation: {
2209
+ body: "\n<StorybookDescriptions componentName={'PageArea'} type={'pageArea'}/>\n<Canvas of={Component.PageAreaBasic}/>\n\n<StorybookDescriptions componentName={'Block'} type={'differences'}/>\n ",
2210
+ slots: "\n<Canvas of={Component.PageAreaSlots}/>\n<StorybookDescriptions componentName={'Slot'} type={'default'}/>\n<StorybookDescriptions componentName={'Slot'} type={'headline'}/>\n<StorybookDescriptions componentName={'Slot'} type={'label'}/>\n<StorybookDescriptions componentName={'Slot'} type={'description'}/>\n<StorybookDescriptions componentName={'Slot'} type={'caption'}/>\n<StorybookDescriptions componentName={'Slot'} type={'trailing'}/>\n "
2211
+ },
2212
+ ai: { description: "\nThe PageArea component serves as a foundational structural unit for application pages.\nIt helps define the main content zones and ensures consistent layout management across different views.\nTypically used as a root-level container within a specific page or sub-section to organize content blocks and handle area-specific logic.\n " }
2213
+ },
2032
2214
  {
2033
2215
  name: "Progress",
2034
2216
  description: {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/wiki",
3
3
  "private": false,
4
- "version": "0.39.8",
4
+ "version": "0.57.0",
5
5
  "type": "module",
6
6
  "description": "Wiki documentation and storybook utilities for DXT UI design system",
7
7
  "keywords": [
@@ -0,0 +1,43 @@
1
+ import {Meta} from '@storybook/addon-docs/blocks'
2
+
3
+ <Meta title='@dxtmisha/en/functional/Composables/useApiAsyncRef - Async Initialization'/>
4
+
5
+ # `useApiAsyncRef`
6
+
7
+ `useApiAsyncRef` is an asynchronous wrapper over [`useApiRef`](./useApiRef.en.mdx) that performs immediate request initialization.
8
+
9
+ Unlike the standard `useApiRef`, which is initialized "lazily" (on the first data access), this method calls `init()` immediately.
10
+
11
+ ## Key Features
12
+ - **Immediate Initialization** — triggers the request as soon as the composable is called.
13
+ - **Synchronous Recovery** — if the data is already in the cache, it is recovered synchronously before any asynchronous actions start.
14
+ - **SSR Support** — utilizes `onServerPrefetch` to ensure data availability before rendering.
15
+
16
+ ## Parameters
17
+ The parameters are identical to `useApiRef`.
18
+
19
+ - `path?: RefOrNormal<string | undefined>` — the endpoint path.
20
+ - `options?: ApiOptions` — request options.
21
+ - `reactivity?: boolean` — whether to enable reactivity.
22
+ - `conditions?: RefType<boolean>` — request conditions.
23
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — data transformation.
24
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — contract validation.
25
+ - `unmounted?: boolean` — removal from cache on unmount.
26
+ - `apiInstance?: ApiInstance` — API instance.
27
+
28
+ ## Return Value
29
+ Returns the `UseApiRef<R>` object. The structure of the `UseApiRef` object is identical to the return value of [`useApiRef`](./useApiRef.en.mdx).
30
+
31
+ ## Example
32
+
33
+ ```typescript
34
+ import { useApiAsyncRef } from '@dxtmisha/functional'
35
+
36
+ // initialization triggers immediately
37
+ const { data, loading } = useApiAsyncRef(
38
+ 'users/list',
39
+ { method: 'GET' }
40
+ )
41
+ ```
42
+
43
+
@@ -0,0 +1,43 @@
1
+ import {Meta} from '@storybook/addon-docs/blocks'
2
+
3
+ <Meta title='@dxtmisha/ru/functional/Composables/useApiAsyncRef - Асинхронная инициализация'/>
4
+
5
+ # `useApiAsyncRef`
6
+
7
+ `useApiAsyncRef` — это асинхронная обертка над [`useApiRef`](./useApiRef.ru.mdx), которая выполняет немедленную инициализацию запроса.
8
+
9
+ В отличие от стандартного `useApiRef`, который инициализируется "лениво" (при первом обращении к данным), этот метод вызывает `init()` сразу.
10
+
11
+ ## Ключевые особенности
12
+ - **Немедленная инициализация** — запускает запрос сразу при вызове хука.
13
+ - **Синхронное восстановление** — если данные уже есть в кэше, они восстанавливаются синхронно до начала любых асинхронных действий.
14
+ - **Поддержка SSR** — использует `onServerPrefetch` для гарантии получения данных при серверном рендеринге.
15
+
16
+ ## Параметры
17
+ Параметры полностью идентичны `useApiRef`.
18
+
19
+ - `path?: RefOrNormal<string | undefined>` — путь к endpoint.
20
+ - `options?: ApiOptions` — опции запроса.
21
+ - `reactivity?: boolean` — включить ли реактивность.
22
+ - `conditions?: RefType<boolean>` — условия выполнения запроса.
23
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — преобразование данных.
24
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — валидация контракта.
25
+ - `unmounted?: boolean` — удаление из кэша при размонтировании.
26
+ - `apiInstance?: ApiInstance` — экземпляр API.
27
+
28
+ ## Возвращаемое значение
29
+ Возвращает объект `UseApiRef<R>`. Состав объекта `UseApiRef` полностью идентичен возвращаемому значению [`useApiRef`](./useApiRef.ru.mdx).
30
+
31
+ ## Пример
32
+
33
+ ```typescript
34
+ import { useApiAsyncRef } from '@dxtmisha/functional'
35
+
36
+ // Инициализация запускается немедленно
37
+ const { data, loading } = useApiAsyncRef(
38
+ 'users/list',
39
+ { method: 'GET' }
40
+ )
41
+ ```
42
+
43
+
@@ -0,0 +1,41 @@
1
+ import {Meta} from '@storybook/addon-docs/blocks'
2
+
3
+ <Meta title='@dxtmisha/vi/functional/Composables/useApiAsyncRef - Khởi tạo bất đồng bộ'/>
4
+
5
+ # `useApiAsyncRef`
6
+
7
+ `useApiAsyncRef` là một wrapper bất đồng bộ phía trên [`useApiRef`](./useApiRef.vi.mdx), thực hiện việc khởi tạo yêu cầu ngay lập tức.
8
+
9
+ Khác với `useApiRef` tiêu chuẩn, vốn được khởi tạo "lười" (chỉ khi truy cập dữ liệu lần đầu), phương thức này gọi `init()` ngay lập tức.
10
+
11
+ ## Các tính năng chính
12
+ - **Khởi tạo ngay lập tức** — kích hoạt yêu cầu ngay khi composable được gọi.
13
+ - **Phục hồi đồng bộ** — nếu dữ liệu đã có trong cache, nó sẽ được phục hồi đồng bộ trước khi bắt đầu bất kỳ hành động không đồng bộ nào.
14
+ - **Hỗ trợ SSR** — sử dụng `onServerPrefetch` để đảm bảo có dữ liệu trước khi render.
15
+
16
+ ## Tham số
17
+ Các tham số hoàn toàn giống với `useApiRef`.
18
+
19
+ - `path?: RefOrNormal<string | undefined>` — đường dẫn endpoint.
20
+ - `options?: ApiOptions` — tùy chọn yêu cầu.
21
+ - `reactivity?: boolean` — có bật tính phản ứng hay không.
22
+ - `conditions?: RefType<boolean>` — điều kiện thực thi.
23
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — chuyển đổi dữ liệu.
24
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — xác thực hợp đồng dữ liệu.
25
+ - `unmounted?: boolean` — có xóa khỏi cache khi unmount hay không.
26
+ - `apiInstance?: ApiInstance` — instance của API.
27
+
28
+ ## Giá trị trả về
29
+ Trả về đối tượng `UseApiRef<R>`. Cấu trúc của đối tượng `UseApiRef` hoàn toàn giống với giá trị trả về của [`useApiRef`](./useApiRef.vi.mdx).
30
+
31
+ ## Ví dụ
32
+
33
+ ```typescript
34
+ import { useApiAsyncRef } from '@dxtmisha/functional'
35
+
36
+ // khởi tạo kích hoạt ngay lập tức
37
+ const { data, loading } = useApiAsyncRef(
38
+ 'users/list',
39
+ { method: 'GET' }
40
+ )
41
+ ```
@@ -1,5 +1,3 @@
1
- import {Meta} from '@storybook/addon-docs/blocks'
2
-
3
1
  <Meta title='@dxtmisha/en/functional/Composables/useApiRef - API Requests'/>
4
2
 
5
3
  # `useApiRef`
@@ -15,7 +13,8 @@ A composable for working with API requests in Vue components. Returns reactive d
15
13
  - `options?: ApiOptions` — request options (`ApiFetch` object or method name string).
16
14
  - `reactivity?: boolean` — automatically re-run the request when `path`, `options`, or locale change. Default: `true`.
17
15
  - `conditions?: RefType<boolean>` — reactive execution condition. If `false` — the request is not made and data is cleared.
18
- - `transformation?: (data: T) => ApiData<R>` — response transformation function applied before saving to `data`.
16
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — response transformation function applied before saving to `data`. Receives the contract validation result as the second argument.
17
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — function to validate the response data contract.
19
18
  - `unmounted?: boolean` — if `true` (default), data is cleared and the watcher is stopped when the component unmounts. When `false`, `EffectScopeGlobal` is used for background persistence.
20
19
  - `apiInstance?: ApiInstance` — API instance to use for the request. Defaults to `Api.getItem()`.
21
20
 
@@ -24,6 +23,8 @@ A composable for working with API requests in Vue components. Returns reactive d
24
23
  Reactive states:
25
24
  - `data: ComputedRef<ApiData<R> | undefined>` — A reference to the loaded data (Computed). Initiates **lazy initialization** (request and watcher) on the first access.
26
25
  - `item: Ref<ApiData<R> | undefined>` — Direct reference to data (Ref). Also initiates lazy initialization upon access.
26
+ - `isResponseContractValid: ComputedRef<boolean>` — `true` if the response contract is valid (`success` status).
27
+ - `responseValidationResult: ComputedRef<ApiDataValidation | undefined>` — the full contract validation result object.
27
28
  - `starting: ComputedRef<boolean>` — Returns `true` if data has never been requested yet or is in the process of fetching the first portion of data (`data` is still `undefined`).
28
29
  - `loading: Ref<boolean>` — Returns `true` if any network request (initial or subsequent `reset`) is currently in progress.
29
30
  - `reading: Ref<boolean>` — A flag for an active data reading/processing process.
@@ -33,7 +34,7 @@ Methods:
33
34
  - `isLoading(): boolean` — A synchronous method that returns the current value of the `loading` flag.
34
35
  - `isReading(): boolean` — A synchronous method that returns the current value of the `reading` flag.
35
36
  - `getItem(): ApiData<R> | undefined` — Method to get the current value of `data` without creating a reactive dependency.
36
- - `init(): void` — Method for explicit request and watcher initialization. Triggered automatically on first access to `data`.
37
+ - `init(awaitFetch?: boolean): Promise<void>` — Method for explicit request and watcher initialization. Triggered automatically on first access to `data`. If `awaitFetch` is `true`, it waits for the first request to complete.
37
38
  - `reset(): Promise<void>` — An asynchronous method to force re-run the request. Cancels the current active request (if any) and initiates a new one.
38
39
  - `stop(): void` — Stops watching reactive dependencies and resets `data` to `undefined`.
39
40
  - `abort(): void` — Cancels the current HTTP request via the internal `AbortController`, while keeping already loaded data in `data`.
@@ -46,6 +47,20 @@ Requests and watching mechanisms **are not started** immediately when `useApiRef
46
47
 
47
48
  `setApiRefGlobalConditions(conditions)` — sets a global condition for all `useApiRef` instances. Only works on the first call.
48
49
 
50
+ ## SSR and Initialization
51
+
52
+ The `init` method is designed to manage the primary data loading process, which is critical for the correct operation of **Server Side Rendering (SSR)** and ensuring fast interface rendering on the client.
53
+
54
+ ### Mechanism of Operation (Hydration)
55
+
56
+ 1. **Server Side (SSR):**
57
+ When the page is first opened, `await init()` should be called in `async setup()`. This forces the server to wait for the API response and render the component with ready-made data. The received data is automatically placed in the state cache, which is then passed to the client.
58
+
59
+ 2. **Client Side (Hydration):**
60
+ When the browser "hydrates" the page, `useApiRef` first checks for data in the cache. If data is there (received from the server), it is immediately applied to `data`, avoiding a duplicate API request.
61
+
62
+ 3. **Dynamic Navigation (Client-side Nav):**
63
+ If the user navigates to the page dynamically (without a page reload), the component renders immediately without waiting for `init()` to complete. This allows for instantly showing a **skeleton** or loading indicator (`loading`) while data is being fetched in the background.
49
64
  ## ApiOptions Object
50
65
 
51
66
  `ApiOptions` — can accept a string with the `method` name (e.g., `'GET'`) or an object of type `ApiFetch`. Fields of the `ApiFetch` object:
@@ -65,6 +80,7 @@ Requests and watching mechanisms **are not started** immediately when `useApiRef
65
80
  - `queryReturn?: (query: Response) => Promise<any>` — response handler instead of standard JSON reading.
66
81
  - `init?: RequestInit` — additional options for native `fetch()` (CORS, cache mode, etc.).
67
82
  - `controller?: AbortController` — controller for canceling the request.
83
+ - `retry?: number` — number of retries on failure.
68
84
 
69
85
  ## Example
70
86
 
@@ -15,15 +15,18 @@ Composable для удобной работы с API-запросами во Vue
15
15
  - `options?: ApiOptions` — опции запроса (объект `ApiFetch` или строка с именем метода).
16
16
  - `reactivity?: boolean` — автоматически перезапускать запрос при изменении `path`, `options` или локали. По умолчанию: `true`.
17
17
  - `conditions?: RefType<boolean>` — реактивное условие выполнения. Если `false` — запрос не выполняется, данные сбрасываются.
18
- - `transformation?: (data: T) => ApiData<R>` — функция преобразования ответа перед сохранением в `data`.
18
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — функция преобразования ответа перед сохранением в `data`. Получает вторым аргументом результат валидации контракта.
19
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — функция для проверки контракта данных ответа.
19
20
  - `unmounted?: boolean` — если `true` (по умолчанию), данные сбрасываются и watcher останавливается при размонтировании компонента. При `false` используется `EffectScopeGlobal` для фоновой работы.
20
21
  - `apiInstance?: ApiInstance` — Экземпляр API, используемый для выполнения запроса. По умолчанию `Api.getItem()`.
21
22
 
22
23
  **Возвращает (`UseApiRef<R>`):**
23
24
 
24
25
  Реактивные состояния:
25
- - `data: ComputedRef<ApiData<R> | undefined>` — Ссылка на загруженные данные (Computed). Инициирует **ленивую инициализацию** (запрос и watcher) при первом обращении.
26
+ - `data: ComputedRef<ApiData<R> | undefined>` — Ссылка на загруженные данные (Computed). Инициирует **ленивую инициализацию** (запрос и watcher) при первым обращении.
26
27
  - `item: Ref<ApiData<R> | undefined>` — Прямая ссылка на данные (Ref). Также инициирует ленивую инициализацию при доступе.
28
+ - `isResponseContractValid: ComputedRef<boolean>` — `true`, если контракт ответа валиден (статус `success`).
29
+ - `responseValidationResult: ComputedRef<ApiDataValidation | undefined>` — полный объект результата валидации контракта.
27
30
  - `starting: ComputedRef<boolean>` — Возвращает `true`, если данные еще ни разу не запрашивались или находятся в процессе получения первой порции данных (`data` еще `undefined`).
28
31
  - `loading: Ref<boolean>` — Возвращает `true`, если в данный момент выполняется любой сетевой запрос (первичный или последующий `reset`).
29
32
  - `reading: Ref<boolean>` — Флаг активного процесса чтения/обработки данных.
@@ -33,7 +36,7 @@ Composable для удобной работы с API-запросами во Vue
33
36
  - `isLoading(): boolean` — Синхронный метод, возвращающий текущее значение флага `loading`.
34
37
  - `isReading(): boolean` — Синхронный метод, возвращающий текущее значение флага `reading`.
35
38
  - `getItem(): ApiData<R> | undefined` — Метод для получения текущего значения `data` без создания реактивной зависимости.
36
- - `init(): void` — Метод для явной инициализации запроса и watchers. Вызывается автоматически при первом обращении к `data`.
39
+ - `init(awaitFetch?: boolean): Promise<void>` — Метод для явной инициализации запроса и watchers. Вызывается автоматически при первом обращении к `data`. Если `awaitFetch` передано как `true`, дожидается выполнения первого запроса.
37
40
  - `reset(): Promise<void>` — Асинхронный метод для принудительного перезапуска запроса. Отменяет текущий активный запрос (если есть) и инициирует новый.
38
41
  - `stop(): void` — Останавливает наблюдение за реактивными зависимостями и сбрасывает `data` в `undefined`.
39
42
  - `abort(): void` — Вызывает отмену текущего HTTP-запроса через внутренний `AbortController`, сохраняя при этом уже загруженные данные в `data`.
@@ -46,6 +49,20 @@ Composable для удобной работы с API-запросами во Vue
46
49
 
47
50
  `setApiRefGlobalConditions(conditions)` — устанавливает глобальное условие для всех экземпляров `useApiRef`. Работает только один раз.
48
51
 
52
+ ## SSR и инициализация
53
+
54
+ Метод `init` предназначен для управления процессом первичной загрузки данных, что критически важно для корректной работы **Server Side Rendering (SSR)** и обеспечения быстрой отрисовки интерфейса на клиенте.
55
+
56
+ ### Механика работы (Hydration)
57
+
58
+ 1. **На стороне сервера (SSR):**
59
+ При первом открытии страницы необходимо вызвать `await init()` в `async setup()`. Это заставит сервер дождаться ответа от API и отрендерить компонент уже с готовыми данными. Полученные данные автоматически попадают в кэш состояния, который передается клиенту.
60
+
61
+ 2. **На стороне клиента (Hydration):**
62
+ Когда браузер "оживляет" (гидрирует) страницу, `useApiRef` первым делом проверяет наличие данных в кэше. Если данные там есть (пришли с сервера), они мгновенно подставляются в `data`, исключая повторный запрос к API.
63
+
64
+ 3. **Динамическая навигация (Client-side Nav):**
65
+ Если пользователь переходит на страницу динамически (без перезагрузки), компонент рендерится сразу, не дожидаясь завершения `init()`. Это позволяет мгновенно показать **скелетон (skeleton)** или индикатор загрузки (`loading`), пока данные подгружаются в фоновом режиме.
49
66
  ## Объект ApiOptions
50
67
 
51
68
  `ApiOptions` — может принимать строку с названием `method` (например, `'GET'`) или объект типа `ApiFetch`. Поля объекта `ApiFetch`:
@@ -65,6 +82,7 @@ Composable для удобной работы с API-запросами во Vue
65
82
  - `queryReturn?: (query: Response) => Promise<any>` — обработчик ответа вместо стандартного чтения JSON.
66
83
  - `init?: RequestInit` — дополнительные опции для нативного `fetch()` (CORS, режим кеша и др.).
67
84
  - `controller?: AbortController` — контроллер для отмены запроса.
85
+ - `retry?: number` — количество повторных попыток при сбое.
68
86
 
69
87
  ## Пример
70
88
 
@@ -15,7 +15,8 @@ Composable để làm việc với các yêu cầu API trong Vue component. Tr
15
15
  - `options?: ApiOptions` — tùy chọn yêu cầu (đối tượng `ApiFetch` hoặc chuỗi tên phương thức).
16
16
  - `reactivity?: boolean` — tự động chạy lại yêu cầu khi `path`, `options` hoặc ngôn ngữ thay đổi. Mặc định: `true`.
17
17
  - `conditions?: RefType<boolean>` — điều kiện thực thi phản ứng. Nếu `false` — yêu cầu không được thực hiện và dữ liệu bị xóa.
18
- - `transformation?: (data: T) => ApiData<R>` — hàm chuyển đổi phản hồi trước khi lưu vào `data`.
18
+ - `transformation?: (data: T, isResponseContractValid?: ApiDataValidation) => ApiData<R>` — hàm chuyển đổi phản hồi trước khi lưu vào `data`. Nhận kết quả xác thực hợp đồng ở đối số thứ hai.
19
+ - `validateResponseContract?: (data: T) => ApiDataValidation` — hàm xác thực hợp đồng dữ liệu phản hồi.
19
20
  - `unmounted?: boolean` — nếu `true` (mặc định), dữ liệu bị xóa và watcher dừng lại khi component unmount. Khi `false`, `EffectScopeGlobal` được sử dụng để duy trì chạy nền.
20
21
  - `apiInstance?: ApiInstance` — Phiên bản API sử dụng cho yêu cầu. Mặc định là `Api.getItem()`.
21
22
 
@@ -24,6 +25,8 @@ Composable để làm việc với các yêu cầu API trong Vue component. Tr
24
25
  Trạng thái phản ứng:
25
26
  - `data: ComputedRef<ApiData<R> | undefined>` — Tham chiếu đến dữ liệu đã tải (Computed). Bắt đầu **khởi tạo lười** (yêu cầu và watcher) khi truy cập lần đầu.
26
27
  - `item: Ref<ApiData<R> | undefined>` — Tham chiếu trực tiếp đến dữ liệu (Ref). Cũng bắt đầu khởi tạo lười khi truy cập.
28
+ - `isResponseContractValid: ComputedRef<boolean>` — `true` nếu hợp đồng phản hồi hợp lệ (trạng thái `success`).
29
+ - `responseValidationResult: ComputedRef<ApiDataValidation | undefined>` — đối tượng kết quả xác thực hợp đồng đầy đủ.
27
30
  - `starting: ComputedRef<boolean>` — Trả về `true` nếu dữ liệu chưa bao giờ được yêu cầu hoặc đang trong quá trình lấy phần dữ liệu đầu tiên (`data` vẫn là `undefined`).
28
31
  - `loading: Ref<boolean>` — Trả về `true` nếu bất kỳ yêu cầu mạng nào (ban đầu hoặc `reset` sau đó) hiện đang được thực hiện.
29
32
  - `reading: Ref<boolean>` — Cờ cho quá trình đọc/xử lý dữ liệu đang hoạt động.
@@ -33,7 +36,7 @@ Phương thức:
33
36
  - `isLoading(): boolean` — Phương thức đồng bộ trả về giá trị hiện tại của cờ `loading`.
34
37
  - `isReading(): boolean` — Phương thức đồng bộ trả về giá trị hiện tại của cờ `reading`.
35
38
  - `getItem(): ApiData<R> | undefined` — Phương thức để lấy giá trị hiện tại của `data` mà không tạo ra phụ thuộc phản ứng.
36
- - `init(): void` — Phương thức để khởi tạo yêu cầu và watcher một cách rõ ràng. Tự động kích hoạt khi truy cập `data` lần đầu.
39
+ - `init(awaitFetch?: boolean): Promise<void>` — Phương thức để khởi tạo yêu cầu và watcher một cách rõ ràng. Tự động kích hoạt khi truy cập `data` lần đầu. Nếu `awaitFetch` là `true`, nó sẽ đợi yêu cầu đầu tiên hoàn thành.
37
40
  - `reset(): Promise<void>` — Phương thức bất đồng bộ để buộc chạy lại yêu cầu. Hủy yêu cầu hiện tại (nếu có) và bắt đầu một yêu cầu mới.
38
41
  - `stop(): void` — Dừng việc theo dõi các phụ thuộc phản ứng và đặt lại `data` thành `undefined`.
39
42
  - `abort(): void` — Hủy yêu cầu HTTP hiện tại thông qua `AbortController` nội bộ, trong khi vẫn giữ lại dữ liệu đã tải trong `data`.
@@ -46,6 +49,20 @@ Yêu cầu và cơ chế theo dõi thay đổi **không được bắt đầu**
46
49
 
47
50
  `setApiRefGlobalConditions(conditions)` — thiết lập điều kiện toàn cục cho tất cả các instance `useApiRef`. Chỉ có hiệu lực một lần.
48
51
 
52
+ ## SSR và Khởi tạo
53
+
54
+ Phương thức `init` được thiết kế để quản lý quá trình tải dữ liệu ban đầu, điều này cực kỳ quan trọng đối với hoạt động chính xác của **Server Side Rendering (SSR)** và đảm bảo giao diện được hiển thị nhanh chóng trên client.
55
+
56
+ ### Cơ chế hoạt động (Hydration)
57
+
58
+ 1. **Phía Máy chủ (SSR):**
59
+ Khi trang được mở lần đầu tiên, hãy gọi `await init()` trong `async setup()`. Điều này buộc máy chủ phải đợi phản hồi từ API và render component với dữ liệu đã sẵn sàng. Dữ liệu nhận được sẽ tự động được đưa vào bộ nhớ đệm trạng thái (cache), sau đó được chuyển đến client.
60
+
61
+ 2. **Phía Máy khách (Hydration):**
62
+ Khi trình duyệt "kích hoạt" (hydrate) trang, `useApiRef` trước tiên sẽ kiểm tra dữ liệu trong bộ nhớ đệm. Nếu dữ liệu có ở đó (được nhận từ máy chủ), chúng sẽ được áp dụng ngay lập tức vào `data`, tránh việc lặp lại yêu cầu API.
63
+
64
+ 3. **Điều hướng Động (Client-side Nav):**
65
+ Nếu người dùng điều hướng đến trang một cách linh hoạt (không tải lại trang), component sẽ render ngay lập tức mà không cần đợi `init()` hoàn thành. Điều này cho phép hiển thị ngay lập tức **skeleton** hoặc chỉ báo đang tải (`loading`) trong khi dữ liệu đang được tải ở chế độ nền.
49
66
  ## Đối tượng ApiOptions
50
67
 
51
68
  `ApiOptions` — có thể nhận một chuỗi tên `method` (ví dụ: `'GET'`) hoặc một đối tượng kiểu `ApiFetch`. Các trường của đối tượng `ApiFetch`:
@@ -65,6 +82,7 @@ Yêu cầu và cơ chế theo dõi thay đổi **không được bắt đầu**
65
82
  - `queryReturn?: (query: Response) => Promise<any>` — trình xử lý phản hồi thay vì đọc JSON tiêu chuẩn.
66
83
  - `init?: RequestInit` — các tùy chọn bổ sung cho `fetch()` gốc (CORS, chế độ cache, v.v.).
67
84
  - `controller?: AbortController` — bộ điều khiển để hủy yêu cầu.
85
+ - `retry?: number` — số lần thử lại khi thất bại.
68
86
 
69
87
  ## Ví dụ
70
88
 
@@ -8,6 +8,7 @@ Creates a computed property that can handle asynchronous getters. Unlike Vue's s
8
8
 
9
9
  **Parameters:**
10
10
  - `getter: (() => Promise<R>) | (() => R) | R` — An async function, synchronous function, or raw value to compute the result from.
11
+ - `initialState?: R` — The initial value of the result.
11
12
  - `ignore?: R` — A value to be ignored (will not be set as the result).
12
13
  - `debugOptions?: DebuggerOptions` — Options used for debugging reactive computations, supported by Vue.js.
13
14
 
@@ -17,6 +18,13 @@ Creates a computed property that can handle asynchronous getters. Unlike Vue's s
17
18
  ```typescript
18
19
  import { computedAsync } from '@dxtmisha/functional'
19
20
 
21
+ // Initial state
22
+ const status = computedAsync(async () => {
23
+ await new Promise(resolve => setTimeout(resolve, 1000))
24
+ return 'online'
25
+ }, 'offline')
26
+ // status.value is 'offline' immediately, and 'online' after 1 second
27
+
20
28
  // Async getter
21
29
  const data = computedAsync(async () => {
22
30
  const response = await fetch('/api/data')
@@ -8,6 +8,7 @@ import { Meta } from '@storybook/addon-docs/blocks'
8
8
 
9
9
  **Параметры:**
10
10
  - `getter: (() => Promise<R>) | (() => R) | R` — Асинхронная функция, синхронная функция или прямое значение для вычисления результата.
11
+ - `initialState?: R` — Начальное значение результата.
11
12
  - `ignore?: R` — Значение, которое должно быть проигнорировано (не будет установлено в результат).
12
13
  - `debugOptions?: DebuggerOptions` — Опции отладки реактивных вычислений Vue.js.
13
14
 
@@ -17,6 +18,13 @@ import { Meta } from '@storybook/addon-docs/blocks'
17
18
  ```typescript
18
19
  import { computedAsync } from '@dxtmisha/functional'
19
20
 
21
+ // Начальное значение
22
+ const status = computedAsync(async () => {
23
+ await new Promise(resolve => setTimeout(resolve, 1000))
24
+ return 'online'
25
+ }, 'offline')
26
+ // status.value будет 'offline' сразу, и 'online' через 1 секунду
27
+
20
28
  // Асинхронный геттер
21
29
  const data = computedAsync(async () => {
22
30
  const response = await fetch('/api/data')
@@ -8,6 +8,7 @@ Tạo một thuộc tính computed có thể xử lý các getter bất đồng
8
8
 
9
9
  **Tham số:**
10
10
  - `getter: (() => Promise<R>) | (() => R) | R` — Hàm bất đồng bộ, hàm đồng bộ, hoặc giá trị trực tiếp dùng để tính toán kết quả.
11
+ - `initialState?: R` — Giá trị ban đầu của kết quả.
11
12
  - `ignore?: R` — Giá trị cần bỏ qua (sẽ không được thiết lập vào kết quả).
12
13
  - `debugOptions?: DebuggerOptions` — Tùy chọn dùng để gỡ lỗi các phép tính phản ứng, được hỗ trợ bởi Vue.js.
13
14
 
@@ -17,6 +18,13 @@ Tạo một thuộc tính computed có thể xử lý các getter bất đồng
17
18
  ```typescript
18
19
  import { computedAsync } from '@dxtmisha/functional'
19
20
 
21
+ // Trạng thái ban đầu
22
+ const status = computedAsync(async () => {
23
+ await new Promise(resolve => setTimeout(resolve, 1000))
24
+ return 'online'
25
+ }, 'offline')
26
+ // status.value là 'offline' ngay lập tức, và 'online' sau 1 giây
27
+
20
28
  // Getter bất đồng bộ
21
29
  const data = computedAsync(async () => {
22
30
  const response = await fetch('/api/data')
@@ -8,6 +8,7 @@ Creates a computed property that is computed on demand and cached. The value is
8
8
 
9
9
  **Parameters:**
10
10
  - `getter: () => Promise<T> | T` — A function that returns the value to be computed (can be synchronous or asynchronous).
11
+ - `initialState?: T` — The initial value of the result.
11
12
 
12
13
  **Returns:**
13
14
  `CustomRef<T>` — A reactive custom ref containing the resolved result of the getter.
@@ -15,6 +16,13 @@ Creates a computed property that is computed on demand and cached. The value is
15
16
  ```typescript
16
17
  import { computedEternity } from '@dxtmisha/functional'
17
18
 
19
+ // Initial state
20
+ const status = computedEternity(async () => {
21
+ await new Promise(resolve => setTimeout(resolve, 1000))
22
+ return 'online'
23
+ }, 'offline')
24
+ // Status.value is 'offline' until the getter resolves
25
+
18
26
  // Async getter - will only be called when 'data.value' is first accessed
19
27
  const data = computedEternity(async () => {
20
28
  const response = await fetch('/api/data')