52 |
53 | ```
54 |
55 | It is important not to forget that these `css` properties must be specified in the global
56 | scope, because they should be available not only to the modal
57 | the window, but also the container itself.
58 |
--------------------------------------------------------------------------------
/docs/examples/simple-modal.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Simple Modal
6 |
7 |
--------------------------------------------------------------------------------
/docs/examples/vue-router-with-modals.md:
--------------------------------------------------------------------------------
1 | # VueRouter with Modals
2 |
3 | It turned out to be problematic on the site to display an example for working with vue-router, but you can familiarize yourself with it by running
4 | `npm run serve` and go to **/vue-router-with-modal**.
5 |
6 | In this example, we'll look at how vue-router integration works and how to use it.
7 |
8 | To work with VueRouter, the library provides the **useModalRouter** method, which is primarily a wrapper for
9 | component. It is with the help of it that our components will be wrapped in modal windows. To use, let's create a simple
10 | config file for vue-router:
11 | ```ts
12 | import {createRouter, createWebHashHistory} from "vue-router"
13 | import {useModalRouter} from "jenesius-vue-mdoal";
14 | import Modal from "./any-modal.vue";
15 |
16 | const routes = [
17 | {
18 | path: "/",
19 | component: SomeComponent
20 | },
21 | {
22 | path: "/users/:id",
23 | component: useModalRouter(Modal) // Step 1
24 | }
25 | ]
26 |
27 | const router = createRouter({
28 | routes,
29 | history: createWebHashHistory()
30 | })
31 |
32 | useModalRouter.init(router); // Step 2
33 |
34 | export default router
35 | ```
36 |
37 | ### Step 1
38 | In the first step, we wrap the component. In fact, this method does the following:
39 | 1. When switching to the specified route, it will show the passed component.
40 | 2. Render always returns *null* as a result.
41 | 3. When leaving the route, the current modal window will be closed.
42 |
43 | ### Step 2
44 | Before work, we must provide a router so that the library can subscribe to state changes
45 | router.
46 |
47 | ----
48 |
49 | Now if we navigate to */users/:id* our modal window will be opened.
50 |
--------------------------------------------------------------------------------
/docs/guide/close-after-route-changed.md:
--------------------------------------------------------------------------------
1 | # Closing modal with vue-router
2 |
3 | By default, the modal doesn't close when the path changes (vue-router). This was done on purpose, because
4 | your project may not have this library or any other one for working with routes. Also this
5 | the function is not heavy even for an entry-level programmer.
6 |
7 | ## Vue Router
8 | So that when closing a modal window using the **vue-router** library, you need to register the following
9 | hook:
10 |
11 | ```ts
12 | import {getCurrentModal, closeModal} from "jenesius-vue-modal";
13 |
14 | const router = new VueRouter({...})
15 |
16 | router.beforeEach(async (to, from, next) => {
17 | // There's some opened modal
18 | if (getCurrentModal()) { // (1)
19 | try {
20 | await closeModal(); // (2)
21 | next(); // (3)
22 | } catch (e) {
23 | // ...
24 | next(false); // (4)
25 | }
26 | } else next();
27 | })
28 | ```
29 |
30 | Let's see what's going on here:
31 | - (1) - If the current modal window is not *undefined* then we need to close all modal windows (2).
32 | - (3) - If the closing was successful, then we confirm the transition to the next route.
33 | - (4) - We disable the transition if the *closeModal* threw an error (the modal window remained open).
--------------------------------------------------------------------------------
/docs/guide/config.md:
--------------------------------------------------------------------------------
1 | # Configuration
2 |
3 | To change the settings `jenesius-vue-modal` you need to use
4 | function `config`. You can influence the handling of pressing `Esc`,
5 | name of animation, `scroll` lock, etc:
6 |
7 | ```ts
8 | import {config} from "jenesius-vue-modal";
9 | config({
10 | // Params
11 | })
12 | ```
13 |
14 | The configuration object has the following properties:
15 |
16 | - **`scrollLock`** Default value is `true`. If installed
17 | value `true`, opening a modal window will block `scroll` on
18 | page.
19 | - **`animation`** Default value is `modal-list`. Used
20 | to set the animation name for `transition-group`. Read more
21 | can be found on [this page](./details-animation).
22 | - **`escClose`** Default value is `true`. Controls closing
23 | modal window by pressing `Esc`.
24 |
25 | :::info For Namespace
26 | If you are working with a different `namespace` than the original one,
27 | you need to take care of the closure yourself.
28 | :::
29 |
30 | - **`backgroundClose`** Default value is `true`. Parameter
31 | is responsible for closing the modal window by clicking on the
32 | darkened background. In
33 | case, if set to `true`, clicking on the back area will
34 | cause the modal window to close.
35 |
36 | - **`skipInitCheck`** Default value is `false`. Is used for
37 | checking for the presence of `container` on the page when the modal is opened
38 | window. When you try to open a modal window you will receive an error
39 | `NotInitilized`. If your project assumes that the container
40 | will create after opening the modal window, you can pass
41 | value `true`. Thus skipping the `container` check procedure.
42 |
43 | - **`store`** Default value is `{}`. Used for storage
44 | modal windows and opening them by key. You can read more in detail
45 | on [here](./store).
46 |
47 | - **`singleShow`** The default value is `false`. Used in case
48 | if you need to show only the last modal window when using several
49 | windows (via `pushModal`). In such a case, if the value is set to true,
50 | When you open a fashion window, all voices will be closed (through the mechanism
51 | `v-show`).
--------------------------------------------------------------------------------
/docs/guide/details-animation.md:
--------------------------------------------------------------------------------
1 | # Animation
2 | If you need to change the animation of showing and hiding the modal, you need
3 | to override some properties and styles. Default for animating modal windows uses
4 | **modal-list** as the animation name. To override the animation name, you need
5 | to specify a new one in the configuration:
6 | ```ts
7 | import {config} from "jenesius-vue-modal";
8 |
9 | config({
10 | animation: "fade" // Any name
11 | })
12 | ```
13 | When changing the animation, it is necessary to take into account that we must
14 | animate both the **.modal-container** and the modal window itself **.modal-item**.
15 |
16 | For example, let's change the animation and the length of the appearance of
17 | the modal window:
18 |
19 | *Instead of fade, you can use modal-list. In this case, you do not need to
20 | redefine the name in the configuration.*
21 |
22 | ```css
23 | /* Don't forget to include the animation time for the start block */
24 | .fade-enter-active,
25 | .fade-leave-active,
26 | .fade-enter-active .modal-item,
27 | .fade-leave-active .modal-item{
28 | transition: 1.2s;
29 | }
30 |
31 | .fade-enter-from .modal-item,
32 | .fade-leave-to .modal-item{
33 | transform: translateX(100px);
34 | }
35 | ```
36 |
37 |
38 |
--------------------------------------------------------------------------------
/docs/guide/details-styles.md:
--------------------------------------------------------------------------------
1 | # Styles
2 |
3 | To control the background and position of the modal window, you need to work
4 | with the css class **.modal-container** . When a modal window is opened, it is
5 | placed container with the aforementioned class. It has the following properties:
6 | ```css
7 | .modal-container{
8 | display: flex;
9 | align-items: center;
10 | justify-content: center;
11 |
12 | background-color: #3e3e3e21;
13 | }
14 | ```
15 | For example, let's change the background of the modal and make it open at the bottom:
16 | ```css
17 | .modal-container{
18 | align-items: flex-end;
19 | background-color: rgba(62, 175, 124, 0.47);
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/docs/guide/event-close.md:
--------------------------------------------------------------------------------
1 | # Event close
2 | **Each close hook** of a modal accepts one *event-close* parameter. This object provides information about
3 | closing the modal window. It currently has the following properties:
4 | - background (*boolean*) Set to true if the modal is closed by clicking on the background.
5 | - esc (*boolean*) Set to true if the modal close process started with *Escape*
6 |
7 | ```ts
8 | {
9 | beforeModalClose(e) {
10 | // e.background
11 | // e.esc
12 | }
13 | }
14 | ```
15 |
16 | ### Handle esc closing
17 | This example demonstrates how to cancel the closing of the modal window on pressing *Escape*:
18 | ```ts
19 | const modal = await openModal(SomeComponent);
20 | modal.onclose = (event) => {
21 | if (event.esc) return false;
22 | // ...
23 | }
24 | ```
25 |
26 | ## Handle background closing
27 | This example demonstrates how to cancel the closing of the modal window on clicking on the background (darkened) background:
28 | ```ts
29 | const modal = await openModal(SomeComponent);
30 | modal.onclose = (event) => {
31 | if (event.background) return false;
32 | // ...
33 | }
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/guide/getting-started.md:
--------------------------------------------------------------------------------
1 | # Getting started
2 |
3 | Jenesius Vue Modal is a lightweight and simple library for working with modal windows in Vue3. It integrates deeply with Vue.js and allows you to create modals of any complexity.
4 |
5 | ## Installation
6 | Npm is recommended for installing a package.
7 | ```shell
8 | npm i jenesius-vue-modal
9 | ```
10 |
11 | ## Connection to page
12 | To get started, we need to initialize modal windows, add a container in which our components will be displayed. We import the container from the library:
13 | ```vue
14 |
15 | // Your HTML
16 |
17 |
18 |
26 | ```
27 |
28 | ## Let's continue
29 |
30 | Everything is ready to work with modal windows. Go to the [methods](./guide-methods.md) tab to learn how to open and
31 | close modal windows. This library provides a wide range of functions for working with modal windows:
32 | - Opening multiple modal windows
33 | - Return value
34 | - Working with events through the `ModalObject` object
35 | - Integration with `vue-router`
36 | - Availability of `namespace` and the ability to open elements in different spaces.
--------------------------------------------------------------------------------
/docs/guide/guide-navigation-guards.md:
--------------------------------------------------------------------------------
1 | # Navigation Guards
2 |
3 | ## Information
4 |
5 | Sometimes it is necessary to catch the closing of a modal and manage
6 | this state. This can be useful to prevent the user from closing the
7 | modal until they have entered input, or to send a request to the
8 | server.
9 |
10 | If the handler returns **false** or **throws an error** , closing
11 | the modal window will be interrupted.
12 |
13 | Jenesius Vue Modal provides three ways to catch closures:
14 |
15 | ## Onclose
16 |
17 | The [openModal](/guide/guide-methods#open-modal)
18 | and [pushModal](/guide/guide-methods#push-modal)
19 | methods return Promise, which, if successful,
20 | will return the [modalObject](/guide/modal-object) object. In order to
21 | catch the closing of
22 | a modal window, you need to add an event **onclose** to this object:
23 |
24 | ```ts
25 | import {openModal} from "jenesius-vue-modal";
26 |
27 | const modal = await openModal(VueComponent);
28 | let count = 5;
29 |
30 | modal.onclose = () => {
31 | count--;
32 | //The modal window will be closed after five attempts.
33 | if (count > 0) return false;
34 | }
35 | ```
36 |
37 | ### Example
38 |
39 | If several modal windows are open, and one of them will have an
40 | onclose handler that returns false, you can close only those modal
41 | windows that were opened after it.
42 |
43 | ```ts
44 | import {pushModal, closeModal} from "jenesius-vue-modal";
45 |
46 | const modal1 = await pushModal(VueComponent);
47 | const modal2 = await pushModal(VueComponent);
48 | const modal3 = await pushModal(VueComponent);
49 |
50 | modal2.onclose = () => false;
51 |
52 | closeModal(); // close only modal3
53 | ```
54 |
55 | ## In-Component Guards
56 |
57 | Finally, the navigation hook can be specified directly in the
58 | component using the following options:
59 |
60 | - beforeModalClose
61 |
62 | ```ts
63 | const Foo = {
64 | template: "...",
65 | beforeModalClose() {
66 | // has access to the context of the component instance this.
67 | }
68 | }
69 | ```
70 |
71 | ## Composition Api
72 |
73 | While you can still use built-in functions, Jenesius Vue Modal
74 | provides functions for the Composition API:
75 |
76 | ```ts
77 | import {onBeforeModalClose} from "jenesius-vue-modal"
78 |
79 | export default {
80 | setup() {
81 | onBeforeModalClose(() => {
82 | const answer = window.confirm(
83 | "Do you really want to leave? You have unsaved changes!"
84 | )
85 | if (!answer) return false
86 | })
87 | }
88 | }
89 | ```
90 |
91 | ## Async Guards
92 |
93 | The navigation hook can be asynchronous. The modal window will be
94 | closed only when it finishes its work:
95 |
96 | ```ts
97 | export default {
98 | async beforeModalClose() {
99 | await updateData();
100 | }
101 | }
102 | ```
103 |
104 | ```ts
105 | const modal = await openModal(Modal);
106 |
107 | modal.onclose = () => {
108 | return new Promise(resolve => {
109 | setTimeout(resolve, 1000); // The modal will be closed after one second.
110 | })
111 | }
112 | ```
113 |
114 | ## Close event
115 |
116 | Each modal close handler get window parameter: event-close
117 |
118 | ```ts
119 | modal.onclose = (event) => {
120 | // ...
121 | }
122 | ```
123 |
124 | This *event* stores information about how the modal window is closed.
125 | Detailed information about it, about the way to prevent
126 | Closing a modal window by background or by pressing the Esc key can be
127 | read [here](/guide/event-close).
128 |
--------------------------------------------------------------------------------
/docs/guide/guide-returned-value.md:
--------------------------------------------------------------------------------
1 | # Return value from Modal
2 |
3 | If we are talking about the return value of modal windows, we must
4 | first understand their essence. By default, modal windows are treated
5 | as a separate layer of logic with their own data model. This approach
6 | is convenient and makes developing a web application with modal
7 | windows safe. This library inherits this concept.
8 | A modal window is a separate logical level that accepts input
9 | parameters and somehow interacts with them.
10 | However, there are times when a modal window is just part of a
11 | process. I sometimes encounter such cases (although I try my best to
12 | avoid them).
13 | I will describe the solutions that I use in my projects. Starting with
14 | the most convenient, ending with those that I would not use:
15 |
16 | ## Using PromptModal
17 |
18 | In vanilla JS, there is a function prompt, which, upon closing the
19 | popup, will wrap the entered value.
20 |
21 | File *ModalCode.vue*
22 |
23 | ```vue
24 |
25 |
26 |
27 |
28 |
41 | ```
42 |
43 | How to use:
44 |
45 | ```ts
46 | import {promptModal} from "jenesius-vue-modal"
47 |
48 | const code = await promptModal(ModalCode);
49 | ```
50 |
51 | What happened in this example:
52 |
53 | - `promptModal` returns a promise that will be fulfilled when
54 | closing the modal window. The result of `promise` will be
55 | the value passed to the `Modal.EVENT_PROMPT` event.
56 | - To describe the modal window, we implemented a simple pass
57 | random value by pressing a button.
58 |
59 | ## Provide Handle
60 |
61 | We can also pass a function to be called inside a modal window (
62 | Reminds me of the React component logic):
63 |
64 | ```ts
65 | const modal = await openModal(Modal, {
66 | handleRequest: (value) => {
67 | // do something
68 | }
69 | })
70 | ```
71 |
72 | And then in the modal:
73 |
74 | ```vue
75 |
76 |
86 | ```
87 |
88 | ## Emit value and closing
89 |
90 | We can also subscribe to an event and react when it is triggered:
91 |
92 | ```vue
93 | // modal.vue
94 |
95 |
96 |
97 | ```
98 |
99 | And when we open modal:
100 |
101 | ```ts
102 | const modal = await openModal(Modal)
103 | modal.on('return', (value) => {
104 | console.log(value); // false
105 | modal.close()
106 | })
107 | ```
108 |
--------------------------------------------------------------------------------
/docs/guide/integration-installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | - Don't forget to [initialize](./getting-started) Jenesius Vue Modal
4 | - When creating router add modal integration:
5 | ```ts
6 | import { createWebHistory, createRouter} from "vue-router";
7 | import {useModalRouter} from "jenesius-vue-modal";
8 |
9 | const routes = [...];
10 | const router = createRouter({
11 | history: createWebHistory(), // Or any other
12 | routes,
13 | });
14 |
15 | useModalRouter.init(router);
16 | ```
17 | Now the modal handler will react to navigation changes.
18 | - Add new route:
19 | ```ts
20 | import Modal from "Modal.vue"
21 |
22 | const routes = [
23 | {
24 | path: "/any-route",
25 | component: useModalRouter(Modal)
26 | }
27 | ]
28 | ```
29 | Now, when switching to **/any-route**, the window that was passed to
30 | **useModalRouter** the modal window will be displayed.
31 |
32 | :::warning router-view
33 | To display modal windows integrated with `vue-router` is not necessary
34 | create `router-view`, because modal windows are displayed in their own
35 | container.
36 | :::
--------------------------------------------------------------------------------
/docs/guide/integration-introduction.md:
--------------------------------------------------------------------------------
1 | #Introduction
2 |
3 | Sometimes there is a need to bind vue-router for display
4 | modal window. To do this you need to write your own
5 | handler for the router and integrate it with
6 | opening/closing a modal window. `jenesius-vue-modal` already has
7 | all this, you just need to connect it.
8 |
9 | For example, a user table was created along the route **/users**.
10 | A modal handler has been added to the **/users/:id** route. Now when
11 | switching to **/users/3** a modal window will open in which
12 | input parameters from the route are available. They will be transferred as
13 | `props`.
14 |
15 | A complete example can be seen at
16 | SandBox([link](https://codesandbox.io/s/vue-modal-router-n9rn94)).
17 | Note the change in `URL`.
--------------------------------------------------------------------------------
/docs/guide/integration-practical.md:
--------------------------------------------------------------------------------
1 | # Particular Qualities
2 | You can use **props** to get input parameters.
3 | ```ts
4 | // user/5
5 | {
6 | props: {
7 | id: String // 5
8 | }
9 | }
10 | ```
11 | Using **beforeRouteEnter** , **beforeRouteUpdate** , **beforeRouteLeave** is not
12 | possible at this stage. I will try to fix this problem shortly.
13 | BeforeModalClose can be used as a temporary solution.
14 |
--------------------------------------------------------------------------------
/docs/guide/modal-object.md:
--------------------------------------------------------------------------------
1 | # Modal
2 |
3 | Methods [openModal](./guide-methods#open-modal),
4 | [pushModal](./guide-methods#push-modal) return `Promise` which
5 | is successful, will return a `Modal` object. This object is a class
6 | modal window and serves to receive or manage the current
7 | condition. This page will list all available methods
8 | and properties.
9 |
10 | ## Properties
11 |
12 | ### `id`
13 |
14 | The field is a unique identifier for the modal window.
15 | Assigned at the time of opening.
16 |
17 | ### `instance`
18 |
19 | An instance of a modal window component. Used to
20 | access `$data`, `$props` and other modal window properties.
21 |
22 | ::: warning
23 | If you get **instance** in your project together in
24 | `
25 | ```
26 |
27 | Let us immediately pay attention to:
28 |
29 | - getting a queue for `notification`.
30 | - display messages in `v-for`.
31 | - We take the message text from props. **It's important** to remember that props are
32 | `ComputedRef`.
33 |
34 | :::info
35 | If instead of `p` you use your own component, then I recommend
36 | use the following:
37 | ```vue
38 |
39 | ...
40 |
44 | ...
45 |
46 | ```
47 | :::
48 |
49 | This completes the `notification` functionality. It remains to connect this
50 | container in your component, for example `App.vue` and call one of
51 | methods for opening a modal window with `namespace: 'notification'`.
--------------------------------------------------------------------------------
/docs/guide/namespace.md:
--------------------------------------------------------------------------------
1 | # Namespace
2 |
3 | This functionality goes beyond the use of modal windows. However,
4 | this mechanism allows you to implement new interface elements, such as
5 | notifications, error display, etc. Using `namespace` you can easily
6 | implement components with similar functionality of modal windows.
7 |
8 | This article will tell you how to use `namespace`, as well as
9 | An example of creating notifications based on a modal window container
10 | will be given.
11 |
12 | ## Initialization
13 |
14 | By default, we create a container without specifying a `namespace`, but we
15 | nothing prevent you from creating a named container:
16 |
17 | ```vue
18 |
19 |
20 |
21 |
24 | ```
25 |
26 | Here we have created a container in which all modal windows will be placed
27 | with `namespace` set to `errors`.
28 |
29 | ## Addition
30 |
31 | Methods [openModal](./guide-methods#open-modal), [pushModal](./guide-methods#push-modal),
32 | [promptModal](./guide-methods#prompt-modal) are also expanded. In the option you can
33 | indicate the `namespace` that will be used:
34 |
35 | ```ts
36 | import Modal from "my-modal.vue"
37 | import {pushModal} from "jenesius-vue-modal"
38 |
39 | pushModal(Modal, {}, { namespace: 'errors' })
40 | ```
41 |
42 | This modal window will be added to the `errors` space and will
43 | be displayed in the appropriate container.
44 |
45 | ## Closing
46 |
47 | Of course, now you need the ability to close not the last modal
48 | window, and the last window from the desired container. Methods
49 | [closeModal](./guide-methods#close-modal),
50 | [popModal](./guide-methods#pop-modal) have been expanded. Now in the options,
51 | passed as the first parameter, you can specify `namespace`:
52 |
53 | ```ts
54 | import {closeModal} from "jenesius-vue-modal"
55 | closeModal({namespace: 'errors'})
56 | ```
57 |
58 | ## Standard interaction
59 |
60 | What you need to understand is that when we don't specify `namespace`, we are working
61 | with `namespace` = `default`. I recommend not specifying it at all if
62 | The `namespace` used is assumed to be the default.
63 |
64 | **It is important** to clarify that only for `namespace` equal to `default`
65 | The `Esc` handler is installed. At the moment the implementation forces
66 | It’s up to you to take care of closing modal windows in containers
67 | other than `default.`
68 |
69 | ## Modal
70 |
71 | In the object returned by the pushModal, openModal, promptModal methods
72 | a `namespace` field has appeared, which will be set automatically
73 | and store the name of the container.
74 |
75 | ```ts
76 | const modal = await pushModal(Modal, {}, { namespace: 'notification' });
77 | modal.namespace // 'notification'
78 | ```
79 |
80 | ## Gets the current modal window.
81 |
82 | The `getCurrentModal` method has been extended. Now first and optional
83 | the parameter is the name `namespace` for which you want to find the last one
84 | open modal window.
85 |
86 | ```ts
87 | getCurrentModal() // Return last opened modal from default namespace
88 | getCurrentModal("notifications") // From namespace: "notifications"
89 | ```
90 |
91 | ## Getting the current queue
92 |
93 | In practice, using the second `modal-container` does not represent
94 | many amenities. Other interface elements are very different from the dialog ones
95 | (modal) windows. Therefore, it will be more convenient for you to use a queue that
96 | stores an array of current elements:
97 |
98 | ```ts
99 | import {getQueueByNamespace} from "jenesius-vue-modal"
100 |
101 | const notifications = getQueueByNamespace("notifications");
102 | ```
103 |
104 | ### Options
105 |
106 | - **namespace** Optional parameter specifying the name `namespace`.
107 |
108 | ### Return
109 |
110 | The method returns a `reactive` array that stores modal windows.
111 | ## Example
112 |
113 |
--------------------------------------------------------------------------------
/docs/guide/store.md:
--------------------------------------------------------------------------------
1 | # Modal storage
2 |
3 | In older versions of this library, opening a modal window was only possible by passing a component.
4 | The approach remains the main one and sow the day, because. gives you more control and order in your code. However, there is
5 | many situations where this approach is not convenient. For example, when developing a library, the question arises:
6 | how to override the opening of modal windows (how to replace the modal window). This is where storage comes in.
7 |
8 | ## Initialization
9 |
10 | To get started, you need to initialize the storage (save the modal windows we need in it). All
11 | this is done using the configuration function:
12 |
13 | ```ts
14 | import {config} from "jenesius-vue-modal";
15 | import ModalConfirm from "./ModalConfirm";
16 | import ModalAlert from "./ModalAlert"
17 |
18 | config({
19 | store: {
20 | confirm: ModalConfirm,
21 | alert: {
22 | component: "ModalAlert"
23 | }
24 | }
25 | })
26 | ```
27 | In this example, we have added two modal windows to the repository:
28 | - by directly transferring components
29 | - in the second case, we specified an object with the `component` property set, this is necessary to set some
30 | properties specifically for this component.
31 |
32 | Now you can open it by name by passing the key there:
33 | ```ts
34 | openModal('confirm');
35 | openModal('alert');
36 | ```
37 |
38 | Of course, *pushModal* and *promptModal* methods also support this functionality.
39 |
40 | ## Checking for a Modal Window
41 | If you are writing a library, for better interoperability, a function has been added that checks for the presence of a modal
42 | windows in storage:
43 | ```ts
44 | import {getComponentFromStore} from "jenesius-vue-modal";
45 | getComponentFromStore('alert') // undefined
46 | getComponentFromStore('confirm') // Component
47 | ```
48 | **Returns** the VueComponent if it was previously initialized in the store, *undefined* otherwise.
49 |
50 | ## Extended component transfer
51 |
52 | In this article, we will consider the case when we, together with components, pass an entire object with the described `component` property.
53 | In this case, we can also specify the following properties:
54 |
55 | - `backgroundClose`
56 | - `draggable`
57 | - `beforeEach`
58 |
59 | All these properties correspond to the parameter from [configuration](./config).
60 |
61 | ```ts
62 | config({
63 | store: {
64 | confirm: {
65 | component: ModalConfirm,
66 | draggable: true,
67 | backgroundClose: false,
68 | beforeEach() {
69 | Logger.write('Attempting to open a confirmation window.')
70 | }
71 | }
72 | }
73 | })
74 | ```
75 |
--------------------------------------------------------------------------------
/docs/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jenesius/vue-modal/9177d8fe34af0f5584df120d49c36f1b336ac6f6/docs/images/logo.png
--------------------------------------------------------------------------------
/docs/images/logo.svg:
--------------------------------------------------------------------------------
1 |
6 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | layout: home
3 |
4 | title: Jenesius vue-modal
5 | titleTemplate: Jenesius Vue Modal & Simple Modal System for Vue
6 |
7 | hero:
8 | name: Jenesius vue-modal
9 | text: Simple Modal System for Vue
10 | tagline: Simple, powerful, and performant.
11 | actions:
12 | - theme: brand
13 | text: Get Started
14 | link: /guide/getting-started
15 | - theme: alt
16 | text: View on GitHub
17 | link: https://github.com/jenesius/vue-modal
18 | features:
19 | - title: So simple
20 | icon: 🚀
21 | details: Just put ModalContainer and then open any components like modal windows.
22 | - title: Built-in and custom
23 | icon: ✍
24 | details: This library don't add any design rules. You can use your components with your css classes.
25 | - title: Abstraction
26 | icon: 🤖
27 | details: There is no need to embed a modal window in the component. Work with it at a different level of abstraction.
28 | - title: Integration with vue-router
29 | icon: 🎢
30 | details: You can connect this library to vue-router to make a more user-friendly interface.
31 | ---
32 |
--------------------------------------------------------------------------------
/docs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "docs",
3 | "private": true,
4 | "type": "module",
5 | "scripts": {
6 | "dev": "vitepress dev",
7 | "build": "vitepress build"
8 | },
9 | "devDependencies": {
10 | "vitepress": "workspace:*"
11 | }
12 | }
--------------------------------------------------------------------------------
/docs/ru/examples/animation.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Кастомные анимации
6 |
7 |
--------------------------------------------------------------------------------
/docs/ru/examples/demo.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Демо
6 |
--------------------------------------------------------------------------------
/docs/ru/examples/list.md:
--------------------------------------------------------------------------------
1 | - [Простое модальное окно](simple-modal.md)
2 | - [Возращение значение из модального окна](prompt-modal.md)
3 | - [Множественные модальные окна](multi-modals.md)
4 | - [vue-router с модальными окнами](vue-router-with-modals.md)
5 | - [Демо](demo.md)
6 | - [Анимации](animation.md)
7 | - [Боковое модальное окно](sidebar.md)
8 |
--------------------------------------------------------------------------------
/docs/ru/examples/multi-modals.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Множественные модальные окна
6 |
7 |
--------------------------------------------------------------------------------
/docs/ru/examples/prompt-modal.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Возвращаемое значение
6 |
7 |
--------------------------------------------------------------------------------
/docs/ru/examples/sidebar.md:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 | -----
8 |
9 | # Боковое окно
10 |
11 | Здесь будет описан пример отображения модального окна сбоку. Для этого
12 | вам не понадобится `js` или настройка проекта. Мы обойдёмся лишь классами
13 | на `css`.
14 |
15 | Мы можем завести следующий класс в `css`:
16 |
17 | ```css
18 | .modal-container:has(.modal-sidebar) {
19 | /*Move modal to right*/
20 | display: grid;
21 | grid-auto-columns: max-content;
22 | justify-content: end;
23 | }
24 |
25 | /*Change animation only for sidebar modal*/
26 | .modal-list-enter-from .modal-sidebar,
27 | .modal-list-leave-to .modal-sidebar{
28 | transform: translateX(100px) !important;
29 | }
30 | ```
31 |
32 | :::info Именование
33 |
34 | - `.modal-container` класс в котором находится модальное окно, оно
35 | используется библиотекой.
36 | - `.modal-sidebar` название класса, которое вы устанавливаете в своей
37 | модальной компоненте.
38 | - `.modal-list-enter-from` и `.modal-list-leave-to` классы анимации,
39 | также создаваемые библиотекой.
40 | :::
41 |
42 |
43 | Здесь мы установили то, что модально окно будет появляться справа.
44 | Теперь в самом модальном окне мы укажем этот класс на самом верхнем
45 | уровне:
46 |
47 | ```vue
48 |
49 |
50 |
51 |
52 |
53 | ```
54 |
55 | Важно не забыть, что данные свойства `css` нужно указывать в глобальной
56 | области видимости, т.к. они должны быть доступны не только модальному
57 | окну, но и самому контейнеру.
58 |
--------------------------------------------------------------------------------
/docs/ru/examples/simple-modal.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | # Простое модальное окно
6 |
7 |
--------------------------------------------------------------------------------
/docs/ru/examples/vue-router-with-modals.md:
--------------------------------------------------------------------------------
1 | # VueRouter с Modals
2 |
3 | На сайте оказалось проблематично отобразить пример работы с vue-router, но ознакомиться с ним можно, запустив
4 | `npm run serve` и перейдите в **/vue-router-with-modal**.
5 |
6 | В этом примере мы рассмотрим, как работает интеграция vue-router и как ее использовать.
7 |
8 | Для работы с VueRouter библиотека предоставляет метод **useModalRouter**, который в первую очередь является оболочкой для
9 | компонент. Именно с его помощью наши компоненты будут обернуты в модальные окна. Для использования давайте создадим простой
10 | конфигурационный файл для vue-router:
11 | ```ts
12 | import {createRouter, createWebHashHistory} from "vue-router"
13 | import {useModalRouter} from "jenesius-vue-modal";
14 | import Modal from "./any-modal.vue";
15 |
16 | const routes = [
17 | {
18 | path: "/",
19 | component: SomeComponent
20 | },
21 | {
22 | path: "/users/:id",
23 | component: useModalRouter(Modal) // Step 1
24 | }
25 | ]
26 |
27 | const router = createRouter({
28 | routes,
29 | history: createWebHashHistory()
30 | })
31 |
32 | useModalRouter.init(router); // Step 2
33 |
34 | export default router
35 | ```
36 |
37 | ### Шаг 1
38 | На первом этапе мы оборачиваем компонент. Фактически этот метод делает следующее:
39 | 1. При переходе на указанный маршрут будет отображаться переданный компонент.
40 | 2. Render всегда возвращает в результате *null*.
41 | 3. При выходе с маршрута текущее модальное окно закроется.
42 |
43 | ### Шаг 2
44 | Перед работой мы должны предоставить маршрутизатор, чтобы библиотека могла подписываться на изменение состояния.
45 | маршрутизатор.
46 |
47 | ----
48 |
49 | Теперь, если мы перейдем к */users/:id*, откроется наше модальное окно, а значение id будет передано в качестве props.
50 |
--------------------------------------------------------------------------------
/docs/ru/guide/close-after-route-changed.md:
--------------------------------------------------------------------------------
1 | # Закрытие модального окна с помощью vue-router
2 |
3 | По умолчанию модальное окно не закрывается при изменении пути (vue-router). Это было сделано намеренно, потому что
4 | в вашем проекте может не быть этой библиотеки или какой-либо другой для работы с маршрутами. Также это
5 | функция не тяжёлая даже для программиста начального уровня.
6 |
7 | ## Vue Router
8 | Для закрытия модального окна с помощью библиотеки **vue-router** нужно прописать следующий хук:
9 |
10 | ```ts
11 | import {getCurrentModal, closeModal} from "jenesius-vue-modal";
12 |
13 | const router = new VueRouter({...})
14 |
15 | router.beforeEach(async (to, from, next) => {
16 | // Есть ли открытые окна
17 | if (getCurrentModal()) { // (1)
18 | try {
19 | await closeModal(); // (2)
20 | next(); // (3)
21 | } catch (e) {
22 | // ...
23 | next(false); // (4)
24 | }
25 | } else next();
26 | })
27 | ```
28 |
29 | Давайте посмотрим, что здесь происходит:
30 | - (1) - Если текущее модальное окно не *undefined*, нам нужно закрыть все модальные окна (2).
31 | - (3) - Если закрытие прошло успешно, то подтверждаем переход на следующий маршрут.
32 | - (4) - Отключаем переход, если *closeModal* выдал ошибку (модальное окно осталось открытым).
--------------------------------------------------------------------------------
/docs/ru/guide/config.md:
--------------------------------------------------------------------------------
1 | # Конфигурация
2 |
3 | Для изменения настроек `jenesius-vue-modal` необходимо воспользоваться
4 | функцией `config`. Вы можете повлиять на обработку нажатия `Esc`,
5 | название анимации, блокировки `scroll` и т.д:
6 |
7 | ```ts
8 | import {config} from "jenesius-vue-modal";
9 | config({
10 | // Параметры
11 | })
12 | ```
13 |
14 | Объект конфигурации имеет следующие свойства:
15 |
16 | - **`scrollLock`** Значение по умолчанию `true`. Если установлено
17 | значение `true`, открытие модального окна блокирует `scroll` на
18 | странице.
19 | - **`animation`** Значение по умолчанию `modal-list`. Используется
20 | для задания имени анимации для `transition-group`. Подробнее прочитать
21 | можно на [этой странице](./details-animation).
22 | - **`escClose`** Значение по умолчанию `true`. Управляет закрытие
23 | модального окна по нажатию на `Esc`.
24 |
25 | :::info Для Namespace
26 | Если вы работаете с `namespace` отличным от первоначального, вам
27 | необходимо позаботиться о закрытии самостоятельно.
28 | :::
29 |
30 | - **`backgroundClose`** Значение по умолчанию `true`. Параметр
31 | отвечает за закрытие модального окна по клику на затемнённый фон. В
32 | случае, если установлено значение `true`, клик по задней области будет
33 | приводить к закрытию модального окна.
34 |
35 | - **`skipInitCheck`** Значение по умолчанию `false`. Используется для
36 | проверки наличия `container` на странице в момент открытия модального
37 | окна. При попытке открытия модального окна будет получена ошибка
38 | `NotInitilized`. Если у вас в проекте предполагается, что контейнер
39 | будет создавать после открытия модального окна, вы можете передать
40 | значение `true`. Тем самым пропуская процедуру проверки `container`.
41 |
42 | - **`store`** Значение по умолчанию `{}`. Используется для хранения
43 | модальных окон и открытия их по ключу. Более подробно можно прочитать
44 | на [здесь](./store).
45 |
46 | - **`singleShow`** Значение по умолчанию `false`. Используется в случае,
47 | если нужно показывать лишь последнее модальное окно при использовании нескольких
48 | окон (через `pushModal`). В таком случае, если значение установлено как `true`,
49 | при открытии модального окна, все предыдущие будут скрываться (через механизм
50 | `v-show`).
--------------------------------------------------------------------------------
/docs/ru/guide/details-animation.md:
--------------------------------------------------------------------------------
1 | # Анимация
2 | Если вам нужно изменить анимацию показа или скрытия модального окна, вам нужно переопределить некоторые свойства и стили.
3 | По умолчанию для анимации модальных окон используется **modal-list** в качестве имени анимации. Чтобы переопределить имя
4 | анимации, вам нужно указать новые в конфигурации:
5 |
6 | ```ts
7 | import {config} from "jenesius-vue-modal";
8 |
9 | config({
10 | animation: "fade" // Любая другая
11 | })
12 | ```
13 | При изменении анимации необходимо учитывать, что мы должны анимировать как **.modal-container**, так и само модальное
14 | окно **.modal-item**.
15 |
16 | Например, изменим анимацию и продолжительность появления модальное окно:
17 |
18 | *Вместо **fade** вы можете использовать **modal-list**. В таком случае вам не нужно переопределять имя в конфигурации.*
19 |
20 | ```css
21 | /* Не забудьте указать время анимации для стартового блока. */
22 | .fade-enter-active,
23 | .fade-leave-active,
24 | .fade-enter-active .modal-item,
25 | .fade-leave-active .modal-item{
26 | transition: 1.2s;
27 | }
28 |
29 | .fade-enter-from .modal-item,
30 | .fade-leave-to .modal-item{
31 | transform: translateX(100px);
32 | }
33 | ```
34 |
35 |
36 |
--------------------------------------------------------------------------------
/docs/ru/guide/details-styles.md:
--------------------------------------------------------------------------------
1 | # CSS стилизация
2 |
3 | Для управления фоном и положением модального окна нужно поработать
4 | с классом CSS **.modal-container**. Когда открывается модальное окно, оно
5 | размещается в контейнере с вышеупомянутым классом. Он имеет следующие свойства:
6 | ```css
7 | .modal-container{
8 | display: flex;
9 | align-items: center;
10 | justify-content: center;
11 |
12 | background-color: #3e3e3e21;
13 | }
14 | ```
15 | Например, давайте изменим фон модального окна и сделаем так, чтобы оно открывалось внизу:
16 | ```css
17 | .modal-container{
18 | align-items: flex-end;
19 | background-color: rgba(62, 175, 124, 0.47);
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/docs/ru/guide/event-close.md:
--------------------------------------------------------------------------------
1 | # Событие close
2 | **Каждый хук закрытия** модального окна принимает один параметр *event-close*. Этот объект предоставляет информацию о
3 | закрытие модального окна. На данный момент он имеет следующие свойства:
4 | - background (*boolean*) Устанавливается в значение **true**, если модальное окно закрывается щелчком по фону.
5 | - esc (*boolean*) Устанавливается в значение true, если процесс модального закрытия начался с *Escape*
6 |
7 | ```ts
8 | {
9 | beforeModalClose(e) {
10 | // e.background
11 | // e.esc
12 | }
13 | }
14 | ```
15 |
16 | ### Отлавливание закрытия через Escape
17 | В этом примере показано, как отменить закрытие модального окна при нажатии *Escape*:
18 | ```ts
19 | const modal = await openModal(SomeComponent);
20 | modal.onclose = (event) => {
21 | if (event.esc) return false;
22 | // ...
23 | }
24 | ```
25 |
26 | ## Отлавливание закрытия через нажатие на фон
27 | В этом примере показано, как отменить закрытие модального окна при нажатии на фон (затемненную часть экрана):
28 | ```ts
29 | const modal = await openModal(SomeComponent);
30 | modal.onclose = (event) => {
31 | if (event.background) return false;
32 | // ...
33 | }
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/ru/guide/getting-started.md:
--------------------------------------------------------------------------------
1 | # Приступим к работе
2 | Jenesius Vue Modal — легкая и простая библиотека для работы с модальными окнами в Vue.js версии **3+**. Она глубоко
3 | интегрируется с Vue.js и позволяет создавать модальные окна любой сложности.
4 |
5 | ## Установка
6 | Для установки пакета рекомендуется использовать Npm.
7 | ```shell
8 | npm i jenesius-vue-modal
9 | ```
10 |
11 | ## Подключение к странице
12 | Для начала нам необходимо инициализировать модальные окна, добавив контейнер, в котором будут отображаться наши
13 | компоненты. Импортируем контейнер из библиотеки:
14 | ```vue
15 |
16 | // Your HTML
17 |
18 |
19 |
27 | ```
28 |
29 | ## Продолжим
30 |
31 | Для работы с модальными окнами всё готово. Переходите во вкладку [методы](./guide-methods.md), чтобы узнать, как открывать и
32 | закрывать модальные окна. Данная библиотека предоставляет широкий набор функций по работе с модальными окнами:
33 | - Открытие нескольких модальных окон
34 | - Возвращение значения
35 | - Работы с событиями через объект `ModalObject`
36 | - Интеграция с `vue-router`
37 | - Наличие `Namespace` и возможность открытия элементов в разных пространствах
--------------------------------------------------------------------------------
/docs/ru/guide/guide-navigation-guards.md:
--------------------------------------------------------------------------------
1 | # Навигационные хуки
2 |
3 | ## Информация
4 |
5 | Иногда необходимо отловить закрытие модального кона. Это может быть
6 | полезно для предотвращения закрытия пользователем
7 | модально, пока они не введут данные или не отправят запрос на сервер.
8 |
9 | Если обработчик возвращает **false** или **выдает ошибку**, закрытие
10 | модальное окно будет прервано.
11 |
12 | Jenesius Vue Modal предоставляет три способа перехвата закрытия:
13 |
14 | ## Onclose
15 |
16 | Методы [openModal](./guide-methods#open-modal)
17 | and [pushModal](./guide-methods#push-modal)
18 | возвращают Promise, который в случае успеха
19 | вернет объект [modalObject](./modal-object). Чтобы поймать закрытие
20 | модальное окно, вам нужно добавить событие **onclose** к этому
21 | объекту:
22 |
23 | ```ts
24 | import {openModal} from "jenesius-vue-modal";
25 |
26 | const modal = await openModal(VueComponent);
27 |
28 | let count = 5;
29 |
30 | modal.onclose = () => {
31 | count--;
32 | if (count > 0) return false; // Модальное окно закроется после пяти попыток.
33 | }
34 | ```
35 |
36 | ### Пример
37 |
38 | Если открыто несколько модальных окон и у одного из них будет
39 | обработчик onclose, возвращающий false, вы сможете
40 | закрыть только те модальные окна, которые были открыты после него.
41 |
42 | ```ts
43 | import {pushModal, closeModal} from "jenesius-vue-modal";
44 |
45 | const modal1 = await pushModal(VueComponent);
46 | const modal2 = await pushModal(VueComponent);
47 | const modal3 = await pushModal(VueComponent);
48 |
49 | modal2.onclose = () => false;
50 |
51 | closeModal(); // закроется только modal3
52 | ```
53 |
54 | ## Хук внутри компоненты
55 |
56 | Наконец, навигационный хук можно указать непосредственно в компоненте,
57 | используя следующие параметры:
58 |
59 | - beforeModalClose
60 |
61 | ```ts
62 | const Foo = {
63 | template: "...",
64 | beforeModalClose() {
65 | // имеет доступ к контексту экземпляра компонента this.
66 | }
67 | }
68 | ```
69 |
70 | ## Composition Api
71 |
72 | Хотя вы по-прежнему можете использовать встроенные функции, Jenesius
73 | Vue Modal предоставляет функции для Composition API:
74 |
75 | ```ts
76 | import {onBeforeModalClose} from "jenesius-vue-modal"
77 |
78 | export default {
79 | setup() {
80 | onBeforeModalClose(() => {
81 | const answer = window.confirm(
82 | "Вы действительно хочешь уйти? У вас есть несохраненные изменения!"
83 | )
84 | if (!answer) return false
85 | })
86 | }
87 | }
88 | ```
89 |
90 | ## Асинхронный хук
91 |
92 | Навигационный хук может быть асинхронным. Модальное окно закроется
93 | только тогда, когда завершит свою работу:
94 |
95 | ```ts
96 | export default {
97 | async beforeModalClose() {
98 | await updateData();
99 | }
100 | }
101 | ```
102 |
103 | ```ts
104 | const modal = await openModal(Modal);
105 |
106 | modal.onclose = () => {
107 | return new Promise(resolve => {
108 | setTimeout(resolve, 1000); // Модальное окно закроется через одну секунду.
109 | })
110 | }
111 | ```
112 |
113 | ## Событие close
114 |
115 | Каждый обработчик модального закрытия получает параметр окна:
116 | event-close
117 |
118 | ```ts
119 | modal.onclose = (event) => {
120 | // ...
121 | }
122 | ```
123 |
124 | Это *событие* хранит информацию о том, как закрывается модальное окно.
125 | Подробная информация о нем, о способах предотвращения
126 | закрытия модального окна при нажатии на фон или по нажатию клавиши Esc
127 | можно прочитать [здесь](./event-close).
128 |
--------------------------------------------------------------------------------
/docs/ru/guide/guide-returned-value.md:
--------------------------------------------------------------------------------
1 | # Возвращение значения
2 |
3 | Если мы говорим о возвращаемом значении модальных окон, мы должны
4 | сначала понять их суть.
5 | По умолчанию модальные окна рассматриваются как отдельный уровень
6 | логики со своей собственной моделью данных.
7 | Такой подход удобен и делает разработку веб-приложения с модальными
8 | окнами безопасной. Эта библиотека наследует
9 | эту концепцию. Модальное окно — это отдельный логический уровень,
10 | принимающий входные параметры и каким-то образом с
11 | ними взаимодействующий. Однако бывают случаи, когда модальное окно
12 | является лишь частью процесса. Я иногда сталкиваюсь с
13 | такими случаями (хотя стараюсь их избегать). Опишу решения, которые
14 | использую в своих проектах. Начиная с самых удобных,
15 | заканчивая теми, которыми я бы не стал пользоваться:
16 |
17 | ## Использование PromptModal
18 |
19 | В VanillaJS есть функция prompt, которая при закрытии всплывающего
20 | окна возвращает введённое значение. Мы также предоставили метод
21 | [`promptModal`](guide-methods.md#prompt-modal) для схожего
22 | функционала:
23 |
24 | Файл *ModalCode.vue*
25 |
26 | ```vue
27 |
28 |
29 |
30 |
31 |
44 | ```
45 |
46 | Как использовать:
47 |
48 | ```ts
49 | import {promptModal} from "jenesius-vue-modal"
50 |
51 | const code = await promptModal(ModalCode);
52 | ```
53 |
54 | Что произошло в этом примере:
55 |
56 | - `promptModal` возвращает обещание, которое будет выполнено при
57 | закрытии модального окна. Результатом `promise` будет
58 | переданное в событие `Modal.EVENT_PROMPT` значение.
59 | - Чтобы описать модальное окно, мы реализовали простую передачу
60 | случайного значения по нажатию на кнопку.
61 |
62 | ## Предоставить Handle
63 |
64 | Мы также можем передать функцию для вызова внутри модального окна:
65 |
66 | ```ts
67 | const modal = await openModal(Modal, {
68 | handleRequest: (value) => {
69 | // Делаем что-то
70 | }
71 | })
72 | ```
73 |
74 | И затем в модальном окне:
75 |
76 | ```vue
77 |
78 |
88 | ```
89 |
90 | ## Передать значение и после этого закрыть окно
91 |
92 | Мы также можем подписаться на событие и реагировать на его срабатывание:
93 |
94 | ```vue
95 | // modal.vue
96 |
97 |
98 |
99 | ```
100 |
101 | И когда мы открываем окно:
102 |
103 | ```ts
104 | const modal = await openModal(Modal)
105 | modal.on('return', (value) => {
106 | console.log(value); // false
107 | modal.close()
108 | })
109 | ```
110 |
--------------------------------------------------------------------------------
/docs/ru/guide/integration-installation.md:
--------------------------------------------------------------------------------
1 | # Установка
2 |
3 | - Не забудьте [проинициализировать](./getting-started) Jenesius Vue Modal
4 | - При создании роутера добавьте модальную интеграцию:
5 | ```ts
6 | import { createWebHistory, createRouter} from "vue-router";
7 | import {useModalRouter} from "jenesius-vue-modal";
8 |
9 | const routes = [...];
10 | const router = createRouter({
11 | history: createWebHistory(),
12 | routes,
13 | });
14 |
15 | useModalRouter.init(router); // !
16 | ```
17 | Теперь модальный обработчик будет реагировать на изменения навигации.
18 | - Добавьте новый маршрут обёрнутый в `useModalRouter`:
19 | ```ts
20 | import Modal from "Modal.vue"
21 |
22 | const routes = [
23 | {
24 | path: "/any-route",
25 | component: useModalRouter(Modal)
26 | }
27 | ]
28 | ```
29 | Теперь при переключении на **/any-route** окно, переданное в
30 | **useModalRouter** будет отображаться модальное окно.
31 |
32 |
33 | :::warning router-view
34 | Для отображения модальных окон интегрируемых с `vue-router` не нужно
35 | создавать `router-view`, т.к. модальные окна отображаются в своём
36 | контейнере.
37 | :::
--------------------------------------------------------------------------------
/docs/ru/guide/integration-introduction.md:
--------------------------------------------------------------------------------
1 | # Введение
2 |
3 | Иногда возникает необходимость связать vue-router для отображения
4 | модального окна. Чтобы сделать это, вам нужно написать собственный
5 | обработчик для маршрутизатора и интегрировать его с
6 | открытием/закрытием модального окна. В `jenesius-vue-modal` уже есть
7 | все это, вам просто нужно подключить его.
8 |
9 | Например, была создана таблица пользователей по маршруту **/users**.
10 | Модальный обработчик был добавлен в маршрут **/users/:id**. Теперь при
11 | переключении на **/users/3** откроется модальное окно, в котором
12 | доступны входные параметры из маршрута. Они будут переданы в качестве
13 | `props`.
14 |
15 | Полный пример можно посмотреть на
16 | SandBox([ссылка](https://codesandbox.io/s/vue-modal-router-n9rn94)).
17 | Обратите внимание на изменение `URL`.
--------------------------------------------------------------------------------
/docs/ru/guide/integration-practical.md:
--------------------------------------------------------------------------------
1 | # Особые качества
2 | Вы можете использовать **props** для получения входных параметров.
3 | ```ts
4 | // user/5
5 | {
6 | props: {
7 | id: String // 5
8 | }
9 | }
10 | ```
11 | Использование **beforeRouteEnter** , **beforeRouteUpdate** , **beforeRouteLeave** не является
12 | возможно на данном этапе. Я постараюсь исправить эту проблему в ближайшее время.
13 | BeforeModalClose можно использовать как временное решение.
14 |
15 |
--------------------------------------------------------------------------------
/docs/ru/guide/modal-object.md:
--------------------------------------------------------------------------------
1 | # Modal
2 |
3 | Методы [openModal](./guide-methods#open-modal),
4 | [pushModal](./guide-methods#push-modal) возвращают `Promise`, которые
5 | в случае успеха вернёт объект `Modal`. Данный объект является классом
6 | модального окна и служит для получения или управления текущим
7 | состоянием. На данной странице будут перечислены все доступные методы
8 | и свойства.
9 |
10 | ## Свойства
11 |
12 | ### `id`
13 |
14 | Поле является уникальным идентификатором модального окна.
15 | Присваивается в момент открытия.
16 |
17 | ### `instance`
18 |
19 | Экземпляр компоненты модального окна. Используется для того, чтобы
20 | получить доступ к `$data`, `$props` и другим свойствам модального окна.
21 |
22 | ::: warning
23 | Если вы получаете **instance** в своем проекте вместе в
24 | `
25 | ```
26 |
27 | Сразу же обращаем внимание на:
28 |
29 | - получение очереди для `notification`.
30 | - выводим сообщения в `v-for`.
31 | - Текст сообщений берём из props. **Важно** помнить, что props является
32 | `ComputedRef`.
33 |
34 | :::info
35 | Если вместо `p` вы будете использовать свою компоненту, то я рекомендую
36 | использовать следующее:
37 | ```vue
38 |
39 | ...
40 |
44 | ...
45 |
46 | ```
47 | :::
48 |
49 | На этом функционал `notification` реализован. Осталось подключить этот
50 | контейнер в вашей компоненте, например `App.vue` и вызвать один из
51 | методов открытия модального окна с `namespace: 'notification'`.
--------------------------------------------------------------------------------
/docs/ru/guide/namespace.md:
--------------------------------------------------------------------------------
1 | # Namespace
2 |
3 | Данный функционал выходит за рамки использования модальных окон. Однако
4 | этот механизм позволяет реализовать новые элементы интерфейса, такие как
5 | уведомления, отображение ошибок и т.д. Используя `namespace` можно легко
6 | реализовать компоненты со схожим функционалом модальных окон.
7 |
8 | В данной статье будет рассказано, как пользоваться `namespace`, а также
9 | будет приведён пример создания уведомлений на базе контейнера модальных окон.
10 |
11 | ## Инициализация
12 |
13 | По умолчанию мы создаём контейнер не указывая `namespace`, однако нам
14 | ничего не мешает создать именованный контейнер:
15 |
16 | ```vue
17 |
18 |
19 |
20 |
23 | ```
24 |
25 | Здесь мы создали контейнер, в который будут помещаться все модальные окна
26 | с установленным `namespace` в `errors`.
27 |
28 | ## Добавление
29 |
30 | Методы [openModal](./guide-methods#open-modal), [pushModal](./guide-methods#push-modal),
31 | [promptModal](./guide-methods#prompt-modal) также расширены. В опции можно
32 | указать тот `namespace`, которые будет использован:
33 | ```ts
34 | import Modal from "my-modal.vue"
35 | import {pushModal} from "jenesius-vue-modal"
36 |
37 | pushModal(Modal, {}, { namespace: 'errors' })
38 | ```
39 |
40 | Данное модальное окно будет добавлено в пространство `errors` и будет
41 | отображаться в соответствующем контейнере.
42 |
43 | ## Закрытие
44 |
45 | Разумеется теперь необходима возможность закрыть не последнее модальное
46 | окно, а последнее окно из нужного контейнера. Методы
47 | [closeModal](./guide-methods#close-modal),
48 | [popModal](./guide-methods#pop-modal) были расширены. Теперь в опциях,
49 | передаваемых первым параметром, можно указать `namespace`:
50 |
51 | ```ts
52 | import {closeModal} from "jenesius-vue-modal"
53 | closeModal({namespace: 'errors'})
54 | ```
55 |
56 | ## Стандартное взаимодействие
57 |
58 | Нужно понимать то, что когда мы не указываем `namespace`, мы работаем
59 | с `namespace` = `default`. Я рекомендую не указывать его вовсе, если
60 | используемый `namespace` предполагается, как по умолчанию.
61 |
62 | **Важно** уточнить то, что только для `namespace` равный `default`
63 | устанавливается обработчик `Esc`. На данный момент реализация вынуждает
64 | вас самим позаботиться про закрытие модальных окон в контейнерах
65 | отличных от `default.`
66 |
67 | ## Modal
68 |
69 | В объекте возвращаемом методами pushModal, openModal, promptModal
70 | появилось поле `namespace`, которое будет устанавливаться автоматически
71 | и хранить название контейнера.
72 |
73 | ```ts
74 | const modal = await pushModal(Modal, {}, { namespace: 'notification' });
75 | modal.namespace // 'notification'
76 | ```
77 |
78 | ## Получение текущего модального окна.
79 |
80 | Метод `getCurrentModal` был расширен. Теперь первый и необязательный
81 | параметр является название `namespace` для которого нужно найти последнее
82 | открытое модальное окно.
83 |
84 | ```ts
85 | getCurrentModal() // Return last opened modal from default namespace
86 | getCurrentModal("notifications") // From namespace: "notifications"
87 | ```
88 |
89 | ## Получение текущей очереди
90 |
91 | В практике использование второго `modal-container` не представляет
92 | много удобств. Другие элементы интерфейса сильно отличаются от диалоговых
93 | (модальных) окон. По этому вам будет удобнее использовать очередь, которая
94 | хранит массив текущих элементов:
95 |
96 | ```ts
97 | import {getQueueByNamespace} from "jenesius-vue-modal"
98 |
99 | const notifications = getQueueByNamespace("notifications");
100 | ```
101 |
102 | ### Параметры
103 |
104 | - **namespace** Необязательный параметр, указывающий название `namespace`.
105 |
106 | ### Return
107 |
108 | Метод возвращает `reactive` массив, который хранит в себе модальные окна.
109 | ## Пример
110 |
111 |
--------------------------------------------------------------------------------
/docs/ru/guide/store.md:
--------------------------------------------------------------------------------
1 | # Модальное хранилище
2 |
3 | В старых версиях этой библиотеки открытие модального окна было возможно только путем передачи компонента.
4 | Подход остаётся основным и на текущий день, т.к. дает вам больше контроля и порядка в вашем коде. Однако существует
5 | много ситуаций, когда этот подход не удобен. Например, при разработке библиотеки возникает вопрос:
6 | как переопределить открытие модальных окон (как заменить модальное окно). Здесь на помощь приходит хранилище.
7 |
8 | ## Инициализация
9 |
10 | Для начала необходимо инициализировать хранилище (сохранить в нем нужные нам модальные окна). Все
11 | это делается с помощью функции конфигурации:
12 |
13 | ```ts
14 | import {config} from "jenesius-vue-modal";
15 | import ModalConfirm from "./ModalConfirm";
16 | import ModalAlert from "./ModalAlert"
17 |
18 | config({
19 | store: {
20 | confirm: ModalConfirm,
21 | alert: {
22 | component: "ModalAlert"
23 | }
24 | }
25 | })
26 | ```
27 | В этом примере мы добавили в хранилище два модальных окна:
28 | - передав напрямую компоненты
29 | - во втором случае, мы указали объект с установленным свойством `component`, это необходимо для установления некоторых
30 | свойств конкретно для данной компоненты.
31 |
32 | Теперь его можно открыть по имени, передав туда ключ:
33 | ```ts
34 | openModal('confirm');
35 | openModal('alert');
36 | ```
37 | Конечно, методы *pushModal* и *promptModal* также поддерживают эту функциональность.
38 |
39 | ## Проверка модального окна
40 | Если вы пишете библиотеку, для лучшей совместимости добавлена функция, проверяющая наличие модального окна в хранилище:
41 | ```ts
42 | import {getComponentFromStore} from "jenesius-vue-modal";
43 | getComponentFromStore('alert') // undefined
44 | getComponentFromStore('confirm') // Component
45 | ```
46 | **Возвращает** компонент VueComponent, если он был ранее инициализирован в хранилище, в противном случае *undefined*.
47 |
48 | ## Расширенная передача компоненты
49 |
50 | В данной артикле рассмотрим случай, когда мы вместе компоненты передаём целый объект с описанным свойством `component`.
51 | В таком случае мы также можем указать следующие свойства:
52 |
53 | - `backgroundClose`
54 | - `draggable`
55 | - `beforeEach`
56 |
57 | Все эти свойства соответствуют параметром из [конфигурации](./config).
58 |
59 | ```ts
60 | config({
61 | store: {
62 | confirm: {
63 | component: ModalConfirm,
64 | draggable: true,
65 | backgroundClose: false,
66 | beforeEach() {
67 | Logger.write('Попытка открыть окно подтверждения.')
68 | }
69 | }
70 | }
71 | })
72 | ```
--------------------------------------------------------------------------------
/docs/ru/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | layout: home
3 |
4 | title: Jenesius vue-modal
5 | titleTemplate: Jenesius Vue Modal & Простая Модальная Система для VueJS
6 |
7 | hero:
8 | name: Jenesius vue-modal
9 | text: Простая Модальная Система для VueJS
10 | tagline: Просто, мощно, and быстро.
11 | actions:
12 | - theme: brand
13 | text: Приступим
14 | link: ru/guide/getting-started
15 | - theme: alt
16 | text: Перейти на GitHub
17 | link: https://github.com/jenesius/vue-modal
18 | features:
19 | - title: Лёгкость использования
20 | icon: 🚀
21 | details: Просто подключите ModalContainer и открывайте компоненты как модальные окна.
22 | - title: Создавай и изменяй
23 | icon: ✍
24 | details: Эта библиотека не добавляет никаких правил дизайна. Вы можете использовать свои компоненты с классами CSS.
25 | - title: Абстракция
26 | icon: 🤖
27 | details: Не нужно встраивать модальное окно в компоненту. Работай с ней на другом уровне абстракции.
28 | - title: Интеграция с vue-router
29 | icon: 🎢
30 | details: Вы можете подключить эту библиотеку к vue-router, чтобы сделать интерфейс более удобным.
31 | ---
32 |
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | ## Examples
2 |
3 | Данная папки содержит примеры работы с модальными окнами. Для такого, чтобы запустить их используйте
4 |
5 | ```shell
6 | npm run serve
7 | ```
--------------------------------------------------------------------------------
/examples/draggable/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
19 |
--------------------------------------------------------------------------------
/examples/multi-modal/README.md:
--------------------------------------------------------------------------------
1 | # Multi modals
2 |
3 | One of the advantages of this library is the ability to open multiple modal windows on top of each other. This approach
4 | is not common, but allows you to design complex logic using simple tools.
5 |
6 | In this example, let's see how this is done:
7 |
8 | 1. Let's create a modal window that will open its duplicate, open the initial window and close all the remaining ones:
9 | ```vue
10 |
11 |
12 |
Is Multi modal
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
25 | ```
26 |
27 | In this example, one of the buttons has a handler for opening another modal window using `pushModal`. This
28 | the function opens a new modal window on top of the existing ones without closing them.
29 |
--------------------------------------------------------------------------------
/examples/multi-modal/main.ts:
--------------------------------------------------------------------------------
1 | import {createApp} from "vue"
2 | import App from "./App.vue";
3 |
4 |
5 | createApp(App)
6 | .mount("#app")
--------------------------------------------------------------------------------
/examples/multi-modal/modal-multi-duplicate.vue:
--------------------------------------------------------------------------------
1 |
2 |
8 | A modal window blocks all other workflows in the top-level program until the modal window is closed, as opposed to modeless dialogs that allow users to operate with other windows. Modal windows are intended to grab the user's full attention. Users may not recognize that a modal window requires their attention, leading to confusion about the main window being non-responsive, or causing loss of the user's data input intended for the main window (see Mode error). In severe cases, the modal window appears behind another window controlled by the same program, potentially rendering the entire program unresponsive until the modal window can be located manually.
9 |
8 |
9 |
10 |
26 |
--------------------------------------------------------------------------------
/examples/prompt-modal/README.md:
--------------------------------------------------------------------------------
1 | ## Prompt Modal
2 |
3 | Currently, work with *promptModal* will be considered.
4 |
5 | This method is used to get data from a modal window in a linear fashion.
6 |
7 | For example, we have a modal window that is only needed to get a one-time password.
8 | This window is not a separate logic, but is used only as a temporary step for data entry.
9 | You may find something in common with the `prompt` function from JavaScript, which returns a string.
10 |
11 | Let's see how it works step by step:
12 |
13 | 1. Let's create a modal window *Modal.vue* for one-time password entry:
14 | ```vue
15 |
16 |
17 |
18 |
19 |
20 |
21 |
37 | ```
38 |
39 | Nothing complicated, two interceptors for pressing Enter and a button and calling `$emit`.
40 |
41 | 2. Open it using *promptModal*:
42 | ```ts
43 | const value = await promptModal(ModalCode)
44 | ```
--------------------------------------------------------------------------------
/examples/prompt-modal/main.ts:
--------------------------------------------------------------------------------
1 | import {createApp} from "vue"
2 | import App from "./App.vue";
3 |
4 | createApp(App)
5 | .mount("#app")
--------------------------------------------------------------------------------
/examples/prompt-modal/modal-code.vue:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
35 |
36 |
--------------------------------------------------------------------------------
/examples/use-namespace/README.md:
--------------------------------------------------------------------------------
1 | # Namespace
2 |
3 | This example demonstrates the possibility of using containers.
4 | This functionality can be convenient in cases when you want
5 | divide application logic into `namespace`. Also, the possibility of receiving
6 | modal window queue states for a specific `namespace` gives
7 | the ability to create your own containers with the logic you need.
8 |
9 | The `App.vue` file shows three containers:
10 |
11 | - The main container that you usually register.
12 | - Name container ``
13 | - Container for notification ``
14 |
15 | ## Main container
16 |
17 | By default, the `openModal`, `pushModal` and other methods work with
18 | him.
19 |
20 | ## Named container
21 |
22 | To make the container named, you need to add the property
23 | `namespace`. Also, when adding a modal window, you need to specify
24 | additional option:
25 | ```ts
26 | openModal(Modal, {}, {
27 | namespace: "notification"
28 | })
29 | ```
30 |
31 | Please note that the mechanism does not work in this container
32 | closing by pressing `Esc`. This is intentional, but in the future
33 | subject to change.
34 |
35 | ## Notification container
36 |
37 | Go inside this component `notification-container.vue`. In it
38 | we get the current queue using the `getQueueByNamespace` method.
39 | Next, we display notifications the way we want.
40 |
--------------------------------------------------------------------------------
/examples/use-namespace/main.ts:
--------------------------------------------------------------------------------
1 | import {createApp} from "vue"
2 | import App from "./App.vue";
3 |
4 | createApp(App)
5 | .mount("#app")
--------------------------------------------------------------------------------
/examples/use-namespace/modal.vue:
--------------------------------------------------------------------------------
1 |
2 |