Passa al contenuto principale
Versione: 2.x

Componenti interattivi

Spesso, hai necessità di attivare componenti interattivi oltre a qualsiasi contenuto/animazione che hai su una determinata pagina. A seconda della natura della tua estensione, potresti voler definire elementi interattivi personalizzati o riutilizzare o estendere quelli esistenti.

All components and utilities from Flarum core and bundled extensions are exported, making them available for reuse in other extensions. A full list is available in our API documentation.

Avvisi​

Alerts are managed by a global instance of AlertManagerState, which is accessible via app.alerts on both the forum and admin frontends. Its public methods are:

  • app.alerts.show aggiungerà un nuovo avviso e restituirà una chiave che può essere utilizzata in seguito per ignorarlo. Ha 3 sovraccarichi:
    • app.alerts.show(children)
    • app.alerts.show(attrs, children)
    • app.alerts.show(componentClass, attrs, children)
  • app.alerts.dismiss(key)ignorerà un avviso attivo con la chiave data, se presente.
  • app.alerts.clear() ignorerà tutti gli avvisi.
  • app.alerts.getActiveAlerts() returns the alerts currently being shown.
  • app.alerts.showLoading() and app.alerts.clearLoading() bracket a slow operation, showing a shared loading alert while it runs. See below.

Loading Indicator​

showLoading() and clearLoading() are a pair: call the first when a slow operation starts and the second when it finishes, including when it fails.

They are reference counted, so concurrent operations share one indicator rather than stacking up several, and the indicator only appears after a short delay. An operation that finishes quickly never shows one at all, which avoids a flicker on every fast request.

app.alerts.showLoading();

try {
await doSomethingSlow();
} finally {
app.alerts.clearLoading();
}

Always clear in a finally, or an early return leaves the count raised and the indicator stuck on screen for the rest of the page's life.

In genere, non avrai bisogno di un componente personalizzato per gli avvisi; tuttavia, se lo desideri, puoi impostarne uno. Probabilmente vorrai che erediti flarum/components/Alert.

I seguenti attributi sono utili da tenere a mente:

  • L'attributo type applicherà la classe css Alert--{type}. success produrrà un avviso verde, error un avviso rosso, ed uno vuoto type ne produrrà uno giallo.
  • L'attributo dismissible determinerà se verrà visualizzato un pulsante di chiusura.
  • L'attributo ondismiss attr può essere utilizzato per fornire un callback che verrà eseguito quando l'avviso viene ignorato.
  • I componenti forniti nell'attributo controls verranno mostrati dopo l'avviso.

Modali​

Modals are managed by a global instance of ModalManagerState, which is accessible via app.modal on both the forum and admin frontends. Its public methods are:

  • app.modal.show(componentClass, attrs, stackModal) will show a modal using the given component class and attrs. By default, showing a modal while another is open replaces it. Pass true as the third argument to stack the new modal on top of the current one instead.
  • app.modal.close() will close the topmost open modal. With stacked modals, this reveals the one underneath rather than closing everything.
  • app.modal.isModalOpen() returns whether any modal is currently open.

show() is asynchronous, and accepts either a modal component class or a function returning a promise of one. The second form is how a modal is code split out of your main bundle, with the manager showing a loading state while the chunk arrives:

app.modal.show(() => import('./components/MyCoolModal'), { attr: 'value' });
Showing a modal from a lifecycle method

Calling app.modal.show() directly inside oncreate, view or another lifecycle method does not work reliably, because of how Mithril handles a redraw triggered during a redraw. Defer it by a tick:

setTimeout(() => app.modal.show(MyCoolModal, { attr: 'value' }), 0);

Al contrario degli avvisi, la maggior parte delle modali utilizzerà una classe personalizzata, che eredita flarum/components/Modal. Per esempio:

import Modal from 'flarum/common/components/Modal';

export default class CustomModal extends Modal {
// All true by default. These control whether the modal can be dismissed via the close button, the Esc key, and clicking the backdrop, respectively.
static isDismissibleViaCloseButton = true;
static isDismissibleViaEscKey = true;
static isDismissibleViaBackdropClick = true;

className() {
// Custom CSS classes to apply to the modal
return 'custom-modal-class';
}

title() {
// Content to show in the modal's title bar
return <p>Custom Modal</p>;
}

content() {
// Content to show in the modal's body
return <p>Hello World!</p>;
}
}

Modals with forms inherit flarum/common/components/FormModal. This class provides a onsubmit method which is called when the submit button is clicked:

import FormModal from 'flarum/common/components/FormModal';

export default class CustomFormModal extends FormModal {
// All true by default. These control whether the modal can be dismissed via the close button, the Esc key, and clicking the backdrop, respectively.
static isDismissibleViaCloseButton = true;
static isDismissibleViaEscKey = true;
static isDismissibleViaBackdropClick = true;

className() {
// Custom CSS classes to apply to the modal
return 'custom-modal-class';
}

title() {
// Content to show in the modal's title bar
return <p>Custom Modal</p>;
}

content() {
// Content to show in the modal's body
return <p>Hello World!</p>;
}

onsubmit() {
// If your modal contains a form, you can add form processing logic here.
}
}

More information about methods available to override is available in our API documentation.

È possibile utilizzare la CLI per generare automaticamente un modale:

$ flarum-cli make frontend modal

Composer​

Poiché Flarum è un forum, abbiamo bisogno di strumenti per consentire agli utenti di creare e modificare post e discussioni. Flarum realizza questo attraverso il componente composer.

The composer is managed by a global instance of ComposerState, which is accessible via app.composer on the forum frontend. I suoi metodi pubblici più importanti sono:

  • app.composer.load(componentClass, attrs) caricherà un nuovo tipo di compositore. Se un compositore è già attivo, verrà sostituito.
  • app.composer.show() mostrerà il compositore se è attualmente nascosto.
  • app.composer.close() chiuderà e ripristinerà il compositore dopo aver confermato con l'utente.
  • app.composer.hide() chiuderà e ripristinerà il compositore senza confermare con l'utente.
  • app.composer.bodyMatches(componentClass, attrs) controllerà se il compositore attualmente attivo è di un certo tipo, e se i suoi attributi corrispondono agli attributi forniti opzionalmente.

L'elenco completo dei metodi pubblici è documentato nei documenti API in alto.

Poiché il compositore può essere utilizzato per varie azioni (avviare una discussione, modificare un post, rispondere a una discussione, ecc.), I suoi campi possono variare a seconda dell'utilizzo. Questo viene fatto suddividendo il codice per ogni utilizzo in una sottoclasse di flarum/components/ComposerBody. Questa classe di componenti deve essere fornita durante il caricamento di un compositore.

Composer Editor​

The actual editor is yet another component, flarum/common/components/TextEditor. Its state can be programatically accessed via an "editor driver", which implements EditorDriverInterface. Questo è accessibile tramite app.composer.editor. Ha una varietà di metodi pubblici che consentono alle estensioni di inserire e modificare programmaticamente i contenuti, le selezioni e la posizione del cursore correnti dell'editor di testo del compositore attivo.