You are here

function pwa_webpush_block_view in Progressive Web App 7.2

Implements hook_block_view().

File

modules/pwa_webpush/pwa_webpush.module, line 321

Code

function pwa_webpush_block_view($delta = '') {
  $block = [];
  if ($delta === 'pwa_webpush_register') {
    $text = variable_get('pwa_webpush_block_register_label', t('Enable notifications'));
    $user_subs = [];

    // Get a list of keys of active subscriptions for this user.
    if (user_is_logged_in()) {
      $user_subs = array_map(function ($sub) {
        return $sub->endpoint_sha256;
      }, pwa_webpush_list_subscriptions([
        $GLOBALS['user']->uid,
      ]));
    }
    $block['content'] = [
      '#access' => _pwa_access_check('access pwa webpush'),
      '#attached' => [
        'js' => [
          [
            'data' => [
              'pwa' => [
                'webpush' => [
                  'applicationServerKey' => variable_get('pwa_webpush_vapid_public', NULL),
                  'userSubscriptions' => (object) $user_subs,
                ],
              ],
            ],
            'type' => 'setting',
          ],
        ],
      ],
      // UI to manage subscription to notifications.
      'button' => [
        'text' => [
          '#type' => 'markup',
          '#markup' => '<button type="button" data-drupal-pwa-webpush-register disabled hidden>' . $text . '</button>',
        ],
        '#attached' => [
          'library' => [
            [
              'pwa_webpush',
              'button',
            ],
          ],
        ],
      ],
      // For anonymous users the subscription code is a little different.
      'anonymous' => [
        '#access' => user_is_anonymous(),
        '#attached' => [
          'library' => [
            [
              'pwa_webpush',
              'anonymous',
            ],
          ],
        ],
      ],
      // React to permission changes.
      'autoregister' => [
        '#access' => variable_get('pwa_webpush_autoregister', TRUE),
        '#attached' => [
          'library' => [
            [
              'pwa_webpush',
              'autoregister',
            ],
          ],
        ],
      ],
    ];
  }
  return $block;
}