NewsResource.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use App\Service\DeepLService;
  7. use Filament\Forms\Components\DatePicker;
  8. use Filament\Forms\Components\FileUpload;
  9. use Filament\Forms\Components\Group;
  10. use Filament\Forms\Components\Radio;
  11. use Filament\Forms\Components\Repeater;
  12. use Filament\Forms\Components\RichEditor;
  13. use Filament\Forms\Components\Section;
  14. use Filament\Forms\Components\Select;
  15. use Filament\Forms\Components\Tabs;
  16. use Filament\Forms\Components\Tabs\Tab;
  17. use Filament\Forms\Components\Textarea;
  18. use Filament\Forms\Components\TextInput;
  19. use Filament\Forms\Form;
  20. use Filament\Forms\Get;
  21. use Filament\Resources\Resource;
  22. use Filament\Tables;
  23. use Filament\Tables\Columns\IconColumn;
  24. use Filament\Tables\Columns\ImageColumn;
  25. use Filament\Tables\Columns\TextColumn;
  26. use Filament\Tables\Filters\SelectFilter;
  27. use Filament\Tables\Table;
  28. use Illuminate\Database\Eloquent\Builder;
  29. use Illuminate\Support\Str;
  30. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  31. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  32. class NewsResource extends Resource
  33. {
  34. protected static ?string $model = News::class;
  35. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  36. protected static ?string $navigationLabel = '最新消息管理';
  37. protected static ?string $navigationGroup = '最新消息';
  38. protected static ?string $modelLabel = '最新消息管理';
  39. protected static ?int $navigationSort = 3;
  40. public static function form(Form $form): Form
  41. {
  42. $editor_toolbar = [
  43. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  44. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  45. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  46. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  47. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  48. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  49. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR,
  50. ];
  51. return $form
  52. ->schema([
  53. //
  54. Tabs::make()->schema([
  55. Tab::make('基本資訊')->schema([
  56. Select::make('news_category_id')->label('分類')->options(function () {
  57. return NewsCategory::pluck('name', 'id');
  58. })->required()
  59. ->columnSpan(1),
  60. DatePicker::make('post_date')->label('發佈日')
  61. ->native(false)
  62. ->closeOnDateSelection()
  63. ->required()
  64. ->columnSpan(1),
  65. Translate::make()->schema(fn(string $locale) => [
  66. TextInput::make('title')->required($locale == 'zh_TW')->label('標題')->columnSpan(1),
  67. TextInput::make('written_by')->required($locale == 'zh_TW')->label('撰文者')->columnSpan(1),
  68. Textarea::make('description')->required($locale == 'zh_TW')->label('簡述')->columnSpan(2),
  69. ])
  70. ->locales(['zh_TW', 'en'])
  71. ->actions([
  72. app(DeepLService::class)->createTranslationAction('Main', ['title', 'written_by', 'description']),
  73. ])->columns(2)
  74. ->columnSpan(2)
  75. ->id('Main-content'),
  76. FileUpload::make('news_img')->label('圖片')
  77. ->directory('news')
  78. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor()
  79. ->columnSpan(2),
  80. Translate::make()->schema(fn(string $locale) => [
  81. TextInput::make('news_img_alt')->label('圖片註釋'),
  82. ])
  83. ->locales(['zh_TW', 'en'])
  84. ->actions([
  85. app(DeepLService::class)->createTranslationAction('NewsImageAlt', ['news_img_alt']),
  86. ])->columnSpan(2)
  87. ->id('Main-alt'),
  88. ])->columns(2),
  89. Tab::make('SEO')->schema([
  90. Translate::make()->schema(fn(string $locale) => [
  91. TextInput::make('meta_title')->label('SEO 標題'),
  92. TextInput::make('meta_keyword')->label('SEO 關鍵字'),
  93. Textarea::make('meta_description')->label('SEO 簡述'),
  94. ])
  95. ->locales(['zh_TW', 'en'])
  96. ->actions([
  97. app(DeepLService::class)->createTranslationAction('Seo', ['meta_title', 'meta_keyword', 'meta_description']),
  98. ])->columnSpanFull(),
  99. FileUpload::make('meta_img')->label('放大預覽圖')
  100. ->directory('news/seo')
  101. ->columnSpan(1)
  102. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->imageEditor()
  103. ->id('Seo'),
  104. ]),
  105. Tab::make('內文編輯')->schema([
  106. Repeater::make('paragraphs')->schema([
  107. TextInput::make('item_key')
  108. ->default(fn() => Str::random())
  109. ->hidden()
  110. ->afterStateHydrated(function (TextInput $component, $state) {
  111. if (empty($state)) {
  112. $component->state(Str::random());
  113. }
  114. }),
  115. Radio::make('paragraph_type')->options([
  116. 1 => '圖片',
  117. 2 => '文字',
  118. // 3 => "影音"
  119. ])->label('')->inline()->default(1)->Live(),
  120. Group::make()->schema([
  121. Section::make('')->schema([
  122. FileUpload::make('img_url')->label('')->directory('news/paragraphs')
  123. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
  124. Translate::make()->schema(fn(string $locale) => [
  125. TextInput::make('img_alt')->label('圖片註釋'),
  126. ])
  127. ->locales(['zh_TW', 'en'])
  128. ->actions([
  129. app(DeepLService::class)->createTranslationAction('ParagraphImgAlt', ['img_alt']),
  130. ])->columnSpan(1)
  131. ->id(fn($get) => 'para_img_' . $get('item_key')),
  132. ]),
  133. ])->visible(fn(Get $get): bool => $get('paragraph_type') == 1),
  134. Group::make()->schema([
  135. Translate::make()->schema(fn(string $locale) => [
  136. RichEditor::make('text_content')
  137. ->toolbarButtons([
  138. 'blockquote',
  139. 'bold',
  140. 'bulletList',
  141. 'h2',
  142. 'h3',
  143. 'italic',
  144. 'link',
  145. 'orderedList',
  146. 'redo',
  147. 'strike',
  148. 'underline',
  149. 'undo',
  150. ])
  151. ->disableToolbarButtons([
  152. 'blockquote',
  153. 'strike',
  154. 'attachFiles',
  155. ])
  156. ->fileAttachmentsDisk('s3')
  157. ->fileAttachmentsDirectory('attachments')
  158. ->fileAttachmentsVisibility('private'),
  159. ])
  160. ->locales(['zh_TW', 'en'])
  161. ->actions([
  162. app(DeepLService::class)->createTranslationAction('ParagraphText', ['text_content']),
  163. ])->columnSpan(1)
  164. ->id(fn($get) => 'para_text_' . $get('item_key')),
  165. ])->visible(fn(Get $get): bool => $get('paragraph_type') == 2),
  166. ])
  167. ->relationship('paragraphs')
  168. ->label('段落')
  169. ->collapsible()
  170. ->reorderableWithButtons()
  171. ->orderColumn('order')
  172. ->cloneable(),
  173. ]),
  174. ])->columnSpanFull(),
  175. ]);
  176. }
  177. public static function table(Table $table): Table
  178. {
  179. return $table
  180. ->columns([
  181. //
  182. TextColumn::make('newsCategory.name')->label('分類')->alignCenter(),
  183. TextColumn::make('title')->label('標題')->alignCenter(),
  184. TextColumn::make('written_by')->label('發佈者')->alignCenter(),
  185. TextColumn::make('post_date')->label('發佈時間')->dateTime('Y/m/d')->alignCenter(),
  186. ImageColumn::make('news_img')->label('列表圖')->alignCenter(),
  187. TextColumn::make('list_audit_state')->label('狀態')->badge()
  188. ->color(fn(string $state): string => match ($state) {
  189. '暫存' => 'warning',
  190. '已發佈' => 'success',
  191. }),
  192. IconColumn::make('on_top')->label('置頂')
  193. ->color(fn(string $state): string => match ($state) {
  194. 1 => 'success',
  195. default => ''
  196. })
  197. ->icon(fn(string $state): string => match ($state) {
  198. 1 => 'heroicon-o-check-circle',
  199. default => ''
  200. })
  201. ->action(function ($record): void {
  202. $record->on_top = !$record->on_top;
  203. $record->save();
  204. }),
  205. TextColumn::make('created_at')->label('建立時間')->dateTime('Y/m/d H:i:s')->alignCenter(),
  206. TextColumn::make('updated_at')->label('更新時間')->dateTime()->alignCenter(),
  207. ])
  208. ->filters([
  209. SelectFilter::make('news_category_id')->label('分類')
  210. ->options(NewsCategory::orderBy('order')->pluck('name', 'id'))
  211. ->attribute('news_category_id'),
  212. SelectFilter::make('post_date')->label('年份')
  213. ->options(News::select(\DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull('post_date')->distinct()->pluck('year', 'year')->toArray())
  214. ->query(
  215. fn(array $data, Builder $query): Builder => $query->when(
  216. $data['value'],
  217. fn(Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value'] . '%')
  218. )
  219. ),
  220. SelectFilter::make('visible')->label('狀態')
  221. ->options([
  222. 0 => '暫存',
  223. 1 => '已發佈',
  224. ])
  225. ->query(
  226. fn(array $data, Builder $query): Builder => $query->when(
  227. $data['value'],
  228. fn(Builder $query, $value): Builder => $query->where('visible', $data['value'])
  229. )
  230. ),
  231. ])
  232. ->actions([
  233. Tables\Actions\EditAction::make(),
  234. Tables\Actions\DeleteAction::make(),
  235. \Filament\Tables\Actions\Action::make('audit')
  236. ->label(fn($record) => match ($record->visible) {
  237. 0 => '發佈',
  238. 1 => '下架',
  239. })
  240. ->color(fn($record) => match ($record->visible) {
  241. 0 => 'warning',
  242. 1 => 'gray',
  243. })
  244. ->icon(fn($record) => match ($record->visible) {
  245. 0 => 'heroicon-m-chevron-double-up',
  246. 1 => 'heroicon-m-chevron-double-down',
  247. })
  248. ->action(function ($record): void {
  249. $record->visible = !$record->visible;
  250. $record->save();
  251. })
  252. ->outlined()
  253. ->requiresConfirmation(),
  254. ])
  255. ->bulkActions([
  256. Tables\Actions\BulkActionGroup::make([
  257. Tables\Actions\DeleteBulkAction::make(),
  258. ]),
  259. ])
  260. ->reorderable('order')
  261. ->defaultSort('order');
  262. }
  263. public static function getRelations(): array
  264. {
  265. return [
  266. //
  267. ];
  268. }
  269. public static function getPages(): array
  270. {
  271. return [
  272. 'index' => Pages\ListNews::route('/'),
  273. 'create' => Pages\CreateNews::route('/create'),
  274. 'edit' => Pages\EditNews::route('/{record}/edit'),
  275. ];
  276. }
  277. }